116–c-sharp-menustrip-and-openfiledialog-example

C sharp menuStrip and c sharp OpenFileDialog are visual controls in C# for adding application menu items and opening files, respectively. C sharp menuStrip is the part of C# Menus & Toolbars Toolbox.

c-charp-menuStrip

C sharp OpenFileDialog is the part of C# Dialog Toolbox.

c-charp-openFileDialog

For filtering files we would like to open, property Filter of the OpenFileDialog must be set to certain values.

FileName:
Filter: Text files|*.txt|All Files|*.*

c-sharp-openFileDialog-properties

Following code opens and reads text file:

using System.IO;

private void openToolStripMenuItem_Click(object sender, EventArgs e)
{

string strFullFileName;
if( openFileDialog1.ShowDialog() == DialogResult.OK )
{

strFullFileName = openFileDialog1.FileName;
StreamReader srFileReader = new StreamReader(strFullFileName);
textBox1.Text = srFileReader.ReadToEnd();
srFileReader.Close();
this.Text = openFileDialog1.SafeFileName;

}

}

For file saving, we need to have saveFileDialog control, with properties similar to OpenFileDialog. Corresponding code for saving file is:

private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{

if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{

StreamWriter swFileWriter;
string strTextToSave = textBox1.Text;
swFileWriter = File.CreateText(saveFileDialog1.FileName);
swFileWriter.Write(strTextToSave);
swFileWriter.Close();

this.Text = System.IO.Path.GetFileName(saveFileDialog1.FileName);

}

}

note: in this example, StreamWriter object was not created by constructor, like StreamReader did, but object was created with CreateText() method of File class.

However, constructor can be used if we want to create utf8 text file. In that case, we need to use FileStream object as well. In FileStream object we define file name and file mode, while in StreamWriter we define encoding (UTF8), and use FileStream for other parameters. Whole code is here:

if( saveFileDialog1.ShowDialog() == DialogResult.OK )
{

string str_file_to_save, str_text_to_save;
str_text_to_save = txtEdit.Text;
str_file_to_save = saveFileDialog1.FileName;

using (FileStream fs_stream = new FileStream(str_file_to_save, FileMode.Create))
{

using (StreamWriter sw_FileWrite = new StreamWriter(fs_stream, Encoding.UTF8))
{

sw_FileWrite.Write(str_text_to_save);
sw_FileWrite.Close();

}

}

}

External links:

C Sharp MenuStrip and OpenFileDialog on Homeandlearn
C Sharp MenuStrip and OpenFileDialog on on Codeproject
C Sharp MenuStrip and OpenFileDialog on Microsoft

Posted in c-sharp-code-examples

Leave a Reply

Your email address will not be published. Required fields are marked *

*