5

I need to implement something similar to Notepads' save option. 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. I would like to save the content of the RichTextBox in text format, by entering the name of file in the Save Dialogue box.

Random Dev
  • 51,810
  • 9
  • 92
  • 119
Shamim Hafiz - MSFT
  • 21,454
  • 43
  • 116
  • 176

6 Answers6

10
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);
  }
}
Overlock
  • 128
  • 7
7

For WPF you should use this 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);
    }
}
Ray
  • 45,695
  • 27
  • 126
  • 169
  • what about saving the content. The XAML tag will possibly open up a Dialog Box, but how is the content supposed to get save? – Shamim Hafiz - MSFT Sep 14 '11 at 12:05
  • @Sam, OpenFile requires less permissions. Also isn't FileOutputStream java?? – Ray Sep 14 '11 at 12:12
  • i use FileOutputStream in C# 2005.Used like this.. java.io.OutputStream ostream = new java.io.FileOutputStream(new java.io.File(FileName)); WorkBook.write(ostream); ostream.close(); – Sam Casil Sep 15 '11 at 00:32
2

This works for text files and was tested in 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);
}
lko
  • 8,161
  • 9
  • 45
  • 62
1

misread the question - Ray's answer is valid for OP

This works only in Windows Forms.

You should take a look at the SaveFileDialog class: 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);
1
SaveFileDialog sfDialog = new SaveFileDialog();
sfDialog.ShowDialog();
OutputStream ostream = new FileOutputStream(new File(sfDialog.FileName));
WorkBook.write(ostream);
ostream.close();
Sam Casil
  • 938
  • 1
  • 11
  • 16
0

There is a SaveFileDialog component which you can use, read here to find out how it works and a working sample.

Waqas
  • 6,812
  • 2
  • 33
  • 50