How to write to file in C#

File output can be used by C# programs to communicate with other programs written in different programming languages, or with human beings.

This post documents my experiences in writing to files in C#.net.

Specifying file access

For file writes, we must use either the Write or the ReadWrite member of the System.IO.FileAccess enumeration to specify write access.

Specifying file mode

Apart from specifying file access, we specify the file mode via one of the members of the System.IO.FileMode enumeration. The file mode determines how the operating system will open the file for our code to write to.

Getting an instance of System.IO.FileStream

As with file creation, there are a few ways gain code access to a file which we intend to write data:

  • Using the System.IO.FileStream constructors.

    FileStream fileStream = new FileStream("techcoil.txt", 
        FileMode.Append, FileAccess.Write);
    
  • Using the static Open method of System.IO.File class.

    FileStream fileStream = File.open("techcoil.txt", 
        FileMode.Append, FileAccess.Write);
    
  • Using the Open method of the System.IO.FileInfo class.

    FileInfo fileInfo = new FileInfo("techcoil.txt");
    FileStream fileStream = fileInfo.Open(FileMode.Append, 
        FileAccess.Write);
    

The above code segments get the operating system to open techcoil.txt for writing to the end of the file. If techcoil.txt does not exist, the operating system will create it.

Writing text data to file

To write text data to the file directly, we can encapsulate it in a System.IO.StreamWriter instance and use the Write or WriteLine method to write text data to the file. The following example writes the current date time to the end of techcoil.txt.

using System;
using System.IO;
using System.Text;

public class WriteTextToFile
{
    public static void Main(string[] args)
    {
        try
        {
            // If techcoil.txt exists, seek to the end of the file,
            // else create a new one.
            FileStream fileStream = File.Open("techcoil.txt",
                FileMode.Append, FileAccess.Write);
            // Encapsulate the filestream object in a StreamWriter instance.
            StreamWriter fileWriter = new StreamWriter(fileStream);
            // Write the current date time to the file
            fileWriter.WriteLine(System.DateTime.Now.ToString());
            fileWriter.Flush();
            fileWriter.Close();
        }
        catch (IOException ioe)
        {
            Console.WriteLine(ioe);
        }
    }
}

Writing binary data to file

To write binary data to file, we can use the Write method of the FileStream instance. As with the previous example, the following code writes the current date time string to the end of techcoil.txt. However, it converts the current date time string as bytes before writing to techcoil.txt.

public class WriteBinaryToFile
{
    public static void Main(string[] args)
    {
        try
        {
            // If techcoil.txt exists, seek to the end of the file,
            // else create a new one.
            FileInfo fileInfo = new FileInfo("techcoil.txt");
            FileStream fileStream = fileInfo.Open(FileMode.Append,
                FileAccess.Write);

            // Get the current date time as a string and add a new line to
            // the end of the string
            String currentDateTimeString = System.DateTime.Now.ToString() 
                + Environment.NewLine;
                
            // Get the current date time string as bytes
            byte[] currentDateTimeStringInBytes 
                = ASCIIEncoding.UTF8.GetBytes(currentDateTimeString);
                
            // Write those bytes to the techcoil.txt
            fileStream.Write(currentDateTimeStringInBytes, 
                0, currentDateTimeStringInBytes.Length);
            fileStream.Flush();
            fileStream.Close();
        }
        catch (IOException ioe)
        {
            Console.WriteLine(ioe);
        } // end try-catch
    } // end public static void Main(string[] args)
} // end public class WriteBinaryToFile

Related posts

About Clivant

Clivant a.k.a Chai Heng enjoys composing software and building systems to serve people. He owns techcoil.com and hopes that whatever he had written and built so far had benefited people. All views expressed belongs to him and are not representative of the company that he works/worked for.