wpf 如何将文本框的内容保存到文本文件中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12618180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to save the content of Textbox into a textfile
提问by Owais Wani
I have a textbox which has some content. I also have a button (SAVE) which shud open the FileSaveDialog and allow the content to be saved in a .txt file.
我有一个包含一些内容的文本框。我还有一个按钮 (SAVE),它可以打开 FileSaveDialog 并允许将内容保存在 .txt 文件中。
XAML:
XAML:
<TextBox Height="93" IsReadOnly="True" Text="{Binding Path=ReadMessage, Mode=TwoWay}" Name="MessageRead" />
<Button Content="Save" Command="{Binding Path=SaveFileCommand}" Name="I2CSaveBtn" />
ViewModel:
视图模型:
private string _readMessage = string.Empty;
public string ReadMessage
{
get
{
return _readMessage;
}
set
{
_readMessage = value;
NotifyPropertyChanged("ReadMessage");
}
}
public static RelayCommand SaveFileCommand { get; set; }
private void RegisterCommands()
{
SaveFileCommand = new RelayCommand(param => this.ExecuteSaveFileDialog());
}
private void ExecuteSaveFileDialog()
{
//What To Do HERE???
}
What I basically need is to read the content of textbox, open a file save dialog and store it in a text file to be saved in my system.
我基本上需要的是读取文本框的内容,打开文件保存对话框并将其存储在要保存在我系统中的文本文件中。
回答by Richard Friend
Using SaveFileDialogyou could do something along these lines
使用SaveFileDialog你可以按照这些方式做一些事情
string fileText = ReadMessage;
SaveFileDialog dialog = new SaveFileDialog()
{
Filter = "Text Files(*.txt)|*.txt|All(*.*)|*"
};
if (dialog.ShowDialog() == true)
{
File.WriteAllText(dialog.FileName, fileText);
}
回答by Aleksandar Stojadinovic
Try something like this:
尝试这样的事情:
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Text file|*.txt";
saveFileDialog1.Title = "Save an Image File";
saveFileDialog1.ShowDialog();
// If the file name is not an empty string open it for saving.
if(saveFileDialog1.FileName != "")
{
System.IO.File.WriteAllText(saveFileDialog1.FileName, MessageRead.Text);
}

