How to use openfile dialog box
In this we will work with openfile and savefile dialogbox. Openfile will open openfile dialogbox and by choosing a file we can open that file and display the text in richtextbox. And when we click savefile it will open savefile dialogbox and we can save the text written in richtextbox.we can save it according to the required extension.
How to use openfile dialog box
In this we will create 2 buttons on whose click openfile dialogbox and savefile dialog box is opened. And a textbox to display the text according to the file selected and also write the text to save it.
When we click the save button savefile dialogbox is opened. The text we want to save we will write it in the richtextbox and then we will click on the save button to save the file at the selected location with the specified name.And a messagebox is displayed which shows that file is created or saved.
When we click the open button openfile dialogbox gets opened and we will select the file which we want to open. Data in the file is displayed in the richtextbox.
// code for the saving the file.
private void buttonsave_Click(object sender, EventArgs e)
{
SaveFileDialog f = new SaveFileDialog();
f.Filter = "txtfile(*.txt)|*.txt|all files(*.*)|*.*";
f.FilterIndex = 1;
f.RestoreDirectory = true;
if (f.ShowDialog() == DialogResult.OK)
{
if (f.FileName != "")
{
FileStream fs = (FileStream)f.OpenFile();
StreamWriter sw = new StreamWriter(fs);
switch (f.FilterIndex)
{
case 1:
this.richTextBoxshowtext.SaveFile(fs, RichTextBoxStreamType.RichNoOleObjs);
break;
case 2:
sw.WriteLine(richTextBoxshowtext.Text);
sw.Close();
fs.Close();
MessageBox.Show("file saved", "My dialogs", MessageBoxButtons.YesNo);
break;
case 3:
this.richTextBoxshowtext.SaveFile(fs, RichTextBoxStreamType.RichText);
break;
}
}
}
}
// code to be written on open button click event
private void buttonopen_Click(object sender, EventArgs e)
{
Stream mystream;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "txtfile(*.txt)|*.txt|all files(*.*)|*.*";
ofd.FilterIndex = 2;
if (ofd.ShowDialog() == DialogResult.OK)
{
if ((mystream = ofd.OpenFile()) != null)
{
StreamReader sr = new StreamReader(ofd.InitialDirectory + ofd.FileName);
while (!sr.EndOfStream)
{
richTextBoxshowtext.Text += sr.ReadLine();
}
}
}
}