Occasionally I like to review the basics to make sure I am still on track and update myself if anything has changed. Today I will be reviewing how to read and write to a file in C#. There are two methods, the easy way and the standard way. The standard way looks a little something like this.
Reading contents from a file:
Writing contents to a file:
FileStream flsFileStream = File.Open("data.tmp", FileMode.Open, FileAccess.ReadWrite); StreamWriter srwWriter = new StreamWriter(flsFileStream); srwWriter.WriteLine("New line to text file.");
If you are looking for less code, this is the easy way to read from a file:
string text = File.ReadAllText(@"C:words.txt");
And this is an easy way to write to a file:
File.WriteAllText(@"C:words.txt", "File contents");