11. February 2014 09:38
File IO handling is a common activity in all programming languages.File IO operations such as Read from a File and Write to file are very easy to handle in C#.
In this example you will see some sample Write to File operations in C#. Here I am explaining of writing to a text file.For write to file in C# we can use StreamWriter class.StreamWriter class has method WriteLine which can be used for writing strings to the text file.
Writing to File In C# Code snippet
StreamWriter streamWriter = new StreamWriter("D:\\test.txt")
Using the above code will ensure that ,if file test.txt not exist then it will create the file.
If it exists already it will overwrite the existing file.
Best way to do the above Write to File code is to use the using statement.Also the second parameter value true is to append the file if it already exist.
using (StreamWriter fileWriter = new StreamWriter("D:\\test.txt",true))
There may be cases that you get exceptions such as File in Use or File locked.Look the article How To handle File IOException to get rid of that.