07 July 2011

.NET - Read/write a file line by line

To read some file line by line using C#.NET, I used this function:
if (File.Exists(App.CUSTOMERS_FILE_NAME)) {
  using (var reader = new StreamReader(App.CUSTOMERS_FILE_NAME)) {
    string line = string.Empty;
    while ((line = reader.ReadLine()) != null) {
      //Process the line
    }
  }
}

writing such a file is just as easy:
using (var writer = new StreamWriter(App.CUSTOMERS_FILE_NAME, false, Encoding.Unicode)) {
  writer.WriteLine("Whatever value");
}
The file will be automatically created if it doesn't exist yet.

No comments:

Post a Comment