[英]How to add Save file Dialog Box using C#
I need to implement something similar to Notepads' save option. 我需要实现类似于Notepads的保存选项。 Assuming I have a button placed next to a RichTextBox
, what I want is, when this button is clicked, a Dialogue box will open up, which will look similar to the one that appears when Save As is clicked. 假设我有一个按钮放在RichTextBox
旁边,我想要的是,当点击这个按钮时,会打开一个对话框,它看起来类似于点击另存为时出现的对话框。 I would like to save the content of the RichTextBox in text format, by entering the name of file in the Save Dialogue box. 我想通过在“ 保存对话框”中输入文件名来以文本格式保存RichTextBox的内容。
private void Save_As_Click(object sender, EventArgs e)
{
SaveFileDialog _SD = new SaveFileDialog();
_SD.Filter = "Text File (*.txt)|*.txt|Show All Files (*.*)|*.*";
_SD.FileName = "Untitled";
_SD.Title = "Save As";
if (__SD.ShowDialog() == DialogResult.OK)
{
RTBox1.SaveFile(__SD.FileName, RichTextBoxStreamType.UnicodePlainText);
}
}
For WPF you should use this SaveFileDialog . 对于WPF,您应该使用此SaveFileDialog 。
var dialog = new Microsoft.Win32.SaveFileDialog();
dialog.Filter = "Rich Text File (*.rtf)|*.rtf|All Files (*.*)|*.*";
dialog.FileName = "Filename.rtf"; //set initial filename
if (dialog.ShowDialog() == true)
{
using (var stream = dialog.OpenFile())
{
var range = new TextRange(myRichTextBox.Document.ContentStart,
myRichTextBox.Document.ContentEnd);
range.Save(stream, DataFormats.Rtf);
}
}
This works for text files and was tested in WPF
. 这适用于文本文件,并在WPF
中进行了测试。
var dialog = new Microsoft.Win32.SaveFileDialog();
dialog.Filter = "Text documents (.txt)|*.txt|All Files (*.*)|*.*";
dialog.FileName = "Filename.txt";
if (dialog.ShowDialog() == true)
{
File.WriteAllText(dialog.FileName, MyTextBox.Text);
}
misread the question - Ray's answer is valid for OP 误读了这个问题 - 雷的回答对OP有效
This works only in Windows Forms. 这仅适用于Windows窗体。
You should take a look at the SaveFileDialog class: http://msdn.microsoft.com/en-us/library/system.windows.forms.savefiledialog.aspx 您应该查看SaveFileDialog类: http : //msdn.microsoft.com/en-us/library/system.windows.forms.savefiledialog.aspx
And save the file using something like this (see here ): 并使用类似的东西保存文件(见这里 ):
rtf.SaveFile(dialog.FileName);
SaveFileDialog sfDialog = new SaveFileDialog();
sfDialog.ShowDialog();
OutputStream ostream = new FileOutputStream(new File(sfDialog.FileName));
WorkBook.write(ostream);
ostream.close();
您可以使用SaveFileDialog
组件, 在此处阅读以了解其工作原理和工作示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.