4221 läsa och skriva till fil i Form

Demonstration av hur man läser och skriver till fil följer.

Be din lärare förklara om filhantering och undantagshantering med try och catch.

public partial class Form1 : Form
{
  public Form1()
  {
    InitializeComponent();
    readFromFile();
  }
  private void readFromFile()
  {
    try
    {
      // Open a stream from file.
      FileStream inStream = new FileStream("data.txt", 
          FileMode.Open, FileAccess.Read);
      // Create a stream reader
      StreamReader reader = new StreamReader(inStream);

      // Read file content

      // All in one go. ALT I
      //string fileText = reader.ReadToEnd();
      // Display file content.        
      //data.Text = fileText;
      // end ALT I

      // Read one line at a time. ALT II
      String row = reader.ReadLine();
      data.Text = "";
      while (row != null)
      {
        data.Text += row + Environment.NewLine;
        row = reader.ReadLine();
      }
      // End ALT II

      // close file
      reader.Dispose();
    }
    catch (FileNotFoundException fileEx)
    {
      MessageBox.Show(fileEx.Message);
    }
    catch (Exception e)
    {
      MessageBox.Show(e.Message);
    }
  }
  private void add_Click(object sender, EventArgs e)
  {
    try
    {
      // Open steam to file and create a file writer
      //  that can append data to file.
      StreamWriter writer;
      writer = new StreamWriter("data.txt", true);
      // append a line to file with name and colour
      writer.WriteLine(name.Text + " " + colour.Text);
      writer.Dispose();
      name.Text = "";
      colour.Text = "";
      readFromFile();
    }
    catch (Exception ex)
    {
      MessageBox.Show(ex.Message);
    }
  }

  private void Form1_Load(object sender, EventArgs e)
  {

  }
}

Se även läroboken:

  • Kapitel 1.11 Undantagshantering
  • Kapitel 4 Filer

Mer information: