Saturday, October 16, 2010

C# Tutorial: Read/Write File [Open/Save File]

Here is the code

using System.IO;
///////////////////////
private void button1_Click(object sender, EventArgs e)
{
    // Show the openFileDialog. When Ok is pressed, read the file and copy its content into the textBox1.
    if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        label1.Text = openFileDialog1.FileName;
        textBox1.Text = File.ReadAllText(label1.Text);  
    }
}

private void button2_Click(object sender, EventArgs e)
{
    // Show the saveFileDialog. When Ok is pressed, save the content of the textBox1 into the chosen file.
    if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        File.WriteAllText(saveFileDialog1.FileName, textBox1.Text);   
    }
}

Or download the solution

6 comments:

  1. How can you make to display the second TextBox?

    ReplyDelete
  2. How can you put a filter on the kind of file that you are going to save?
    An example will be like in the pictures, jpg,gif,png,etc.

    ReplyDelete
    Replies
    1. Filter property represents the filter on an open file dialog that is used to filter the type of files to be loaded during the browse option in an open file dialog.
      For example, if you need users to restrict to text files only, we can set Filter property to load text files only.

      SaveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";

      Delete
  3. Sir do you have an tutorial that all games will be save in the application? Please help.

    ReplyDelete