A .NET Technology blog | .NET,C# Progamming,C# tutorials,WPF WCF|Software Engineer


Writing to File In C#

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")
streamWriter .WriteLine("Line1");
streamWriter .WriteLine("Line2");

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))
    fileWriter .WriteLine("Line1");
    fileWriter .WriteLine("Line2");


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.

Add comment

  Country flag

  • Comment
  • Preview