如何使用C#添加保存文件对话框

时间:2011-09-14 11:55:45

标签: c# wpf richtextbox savefiledialog notepad

我需要实现与 Notepads'保存选项类似的功能。假设我在RichTextBox旁边放了一个按钮,我想要的是,当点击这个按钮时,会打开一个对话框,它看起来类似于另存为时出现的那个点击。我想通过在保存对话框中输入文件名来以文本格式保存RichTextBox的内容。

6 个答案:

答案 0 :(得分:9)

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);
  }
}

答案 1 :(得分:7)

对于 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);
    }
}

答案 2 :(得分:2)

这适用于文本文件,并已在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);
}

答案 3 :(得分:1)

误读了这个问题 - Ray的答案对OP

有效

这仅适用于Windows窗体。

您应该查看SaveFileDialog类:http://msdn.microsoft.com/en-us/library/system.windows.forms.savefiledialog.aspx

使用类似的内容保存文件(请参阅here):

rtf.SaveFile(dialog.FileName);

答案 4 :(得分:1)

SaveFileDialog sfDialog = new SaveFileDialog();
sfDialog.ShowDialog();
OutputStream ostream = new FileOutputStream(new File(sfDialog.FileName));
WorkBook.write(ostream);
ostream.close();

答案 5 :(得分:0)

您可以使用SaveFileDialog组件,请阅读here以了解其工作原理和工作示例。