Zebra0.com

csharp files

Write to a File

The first example shows a very simple way to write the contents of an array to a file. There is nothing here to indicate when this will take place.

string[] months = { "January", "February","March","April","May","June","July","August","September","October","November","December"};
System.IO.File.WriteAllLines(@"C:\mydata\months.txt", months);

The second example shows a very simple way to write the contents of a combo box to a file.

 using (System.IO.StreamWriter file =
 new System.IO.StreamWriter(@"C:\mydata\animals.txt"))
 {
          foreach (string item in cboAnimals.Items)
          {
               file.WriteLine(item);
          }
}

There is noting here to indicate when this would occur, or how the file name is selected.

Also, there is no provision for what to do if the file already exists. We will address these issues in the next page.

Experiment:

Use the example to write an actual program to write data to a file.
Make sure that you use filenames that do not already exist, to prevent valuable data being overwritten.

End of lesson, Next lesson: