Loading ...

How to Write to a file in c#

0 (0votes)


Before we start with how to write to a file in C# one should know about File, FileStream and StreamWriter classes and the methods and properties they have. Also about FileAccess and FileMode enumeration. In order to write to a file, we need to open the file for writing. It is similar to opening a file for reading.
For Ex:

FileStream fstream= File.Create(@"c:\samplefile.txt");

It creates a new file with a FileStream object ready to be written to. The contents can be written into the file by calling the Write or WriteByte methods of FileStream class.

How to Write to a file by using the StreamWriter class

StreamWriter swriter= new StreamReader(fstream);
swr.Write("Test file");

The StreamWriter can be used to write directly into the file.It is similar to reading a file. The File class has the CreateText method which can be used for writing directly into the object of StreamWriter.

StreamWriter swriter= File.CreateText(@"C:\samplefile.txt");
swriter.WriteLine("Test file");

The File class has the WriteAllText method that writes the contents of a string into the file and closes the file.

File.WriteAllText(@"c:\sampletest.txt","test file");

How to Write to an existing file

To write to an existing file we need to first open the file. Opening of a file can be done with the help of Open method of File class but we need to mention that we want to write to the stream.

FileStream fstream=null;


FileMode.Open :- It opens an existing file and if the file doesn't exist it throws an exception.
FileAccess.Write :- It specifies the file to be opened to be written to. The file is only appended to and not read only

File class has the OpenWrite method which can be used in place of first opening the file and then writing into the opening file. Instead of calling the Open method of the File class and telling it that you want to open it for writing . We can directly user the OpenWrite method.


But there is one problem with this method. It works only if file exists.

Sometimes we need to create a file first so OpenWrite method will not work although we can write the code to check for the existence of file and create the file if it doesn't exist. But we can use the Open method of File class to avoid writng the code manually .


So the FileMode enumeration value allows to avoid writing code for dealing with a new or existing file.


Comments (no comments yet)

  • :*
  • :*
  • :

Top Posts