While opening . . .
private void OpenFile()
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Open File";
ofd.FileName = "";
ofd.Filter = "Rich Text Files (*.rtf)|*.rtf|Text Document (*.txt)|*.txt|Microsoft Word Document (*.doc)|*.doc|Hypertext Markup Language Document (*.html)|*.html";
ofd.ShowDialog();
try
{
// just one line is added
this.Text = string.Format("{0} - MyNotepad", Path.GetFileName(ofd.Filename));
richTextBoxPrintCtrl1.Text = ofd.FileName;
StreamReader stread = new StreamReader(richTextBoxPrintCtrl1.Text);
richTextBoxPrintCtrl1.Text = stread.ReadToEnd();
stread.Close();
richTextBoxPrintCtrl1.LoadFile(fileName, RichTextBoxStreamType.RichText);
}
catch { }
}
While saving . . .
private void SaveFileAs()
{
SaveFileDialog sfdSaveFile = new SaveFileDialog();
sfdSaveFile.Title = "Save File";
sfdSaveFile.FileName = "Untitled";
sfdSaveFile.Filter = "Rich Text Files (*.rtf)|*.rtf|Text Document (*.txt)|*.txt|Microsoft Word Document (*.doc)|*.doc|Hypertext Markup Language Document (*.html)|*.html";
if (sfdSaveFile.ShowDialog() == DialogResult.OK)
try
{
richTextBoxPrintCtrl1.SaveFile(sfdSaveFile.FileName, RichTextBoxStreamType.RichText);
filepath = sfdSaveFile.FileName;
// just one line is added
this.Text = string.Format("{0} - MyNotepad", Path.GetFileName(sfd.Filename));
}
catch (Exception exc)
{
}
}
Just an update
Toby- The empty catch blocks are needed. If the user cancels the ofd or sfd without the catch block, the program crashes. It keeps the program from crashing
You do not need the catch block to check if User selected OK / Cancel.
OpenFileDialog & SaveFileDialog has method ShowDialog
that returns DialogResult
and value of DialogResult.OK tells that user has selected file to open / save and has not cancelled the operation.
And example with OpenFile
private void OpenFile()
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Open File";
ofd.FileName = "";
ofd.Filter = "Rich Text Files (.rtf)|.rtf|Text Document (.txt)|.txt|Microsoft Word Document (.doc)|.doc|Hypertext Markup Language Document (.html)|.html";
if (ofd.ShowDialog() == DialogResult.OK)
{
// just one line is added
this.Text = string.Format("{0} - MyNotepad", Path.GetFileName(ofd.Filename));
richTextBoxPrintCtrl1.Text = ofd.FileName;
StreamReader stread = new StreamReader(richTextBoxPrintCtrl1.Text);
richTextBoxPrintCtrl1.Text = stread.ReadToEnd();
stread.Close();
richTextBoxPrintCtrl1.LoadFile(fileName, RichTextBoxStreamType.RichText);
}
}