Book Store  
  Contact Us  
  Links  
  Site Map  
C# Tutorials - File Handling

File Handling in C#

 

You can use C# to store data in text and binary files and write programs to read the data from the files.

Writing to a File

   public class WriteFile
    {

        public WriteFile()
        {
            StreamWriter myFile = File.CreateText("hello.txt");

            myFile.WriteLine("Hello");
            myFile.WriteLine("This is a text file");
            myFile.WriteLine("Goodbye");
            myFile.Close();
        }

    }

To work with files make sure that you have the System.IO namespace available to your code. This namespace gives you access to the File and StreamWriter classes which provide useful services for creating and manipulating files.

Notice that you don't have to create a new object instance of the StreamWriter class

In the example above, the text file that is created is called 'hello.txt' although any valid filename can be used.

The WriteLine() method of the StreamWriter class is used to save the data and works in the same way as the equivalent method of the Console class, including outputting values stores in variables using he {0} placeholders.

When you run your program the file will be created in the same location as where the program executable is located, which will be /bin/debug/ folder or /bin/release/ folder.

Reading from a file

Now that you have a file on disc, you will want to open the file and read the data.

    public class ReadFile
    {

        public ReadFile()
        {

            string text;
            
            if (File.Exists("hello.txt"))
            {

            StreamReader myFile = File.OpenText("hello.txt");
            while ((text = myFile.ReadLine()) != null)
            {
                Console.WriteLine(text);
            }
            myFile.Close();
            }
            else
            {
                Console.WriteLine("File does not exists");
            }
        }

    }

We use the StreamReader class to perform the read operations. The text file is read into the object and then the ReadLine() method is used to read each line into the 'text' variable until the end of the file is found.

Checking if a file exists

A simple addition to the above will allow you to check if a file exists before you perform any operations on it.

The static method of the File class called Exists() returns a Boolean value indicating whether or not the specified file, and or file path, exists.

An alternative to Text Files : Binary Files

Storing data in binary format is a method that you may want to use when you have large text files. Binary files are smaller and so more efficient than text files.

    //Write a binary file
    public class WriteFileBinary
    {

        public WriteFileBinary()
        {

            string name;
            int[] scores = new int[3];

            Console.WriteLine("Enter your student name :");
            name = Console.ReadLine();

            for (int i = 0; i < 3; i++)
            {
                Console.WriteLine("Enter score {0} ", i+1);
                scores[i] = Convert.ToInt32(Console.ReadLine());
            }

            FileStream myFile = new FileStream("hello.bin", FileMode.Create);

            BinaryWriter filedata = new BinaryWriter(myFile);

            filedata.Write(name);

            for (int i = 0; i < 3; i++)
            {
                filedata.Write(scores[i]);
            }

            filedata.Close();
            myFile.Close();

        }

    }


    //Read a binary file
    public class ReadFileBinary
    {

        public ReadFileBinary()
        {

            string name;
            int[] scores = new int[3];

            FileStream myFile = new FileStream("hello.bin", FileMode.Open);

            BinaryReader filedata = new BinaryReader(myFile);

            name = filedata.ReadString();

            for (int i = 0; i < 3; i++)
            {
                scores[i] = filedata.ReadInt32();
            }

            filedata.Close();
            myFile.Close();


            Console.WriteLine("Information from file");
            Console.WriteLine("Name {0} :", name);
            for (int i = 0; i < 3; i++)
            {
                Console.WriteLine("Score {0}, {1}", i + 1, scores[i]);
            }

        }

    }

The above two classes illustrate using the BinaryReader and BinaryWriter classes. It also uses the FileStream class to handle the opening and closing of the files.

The FileStream constructor takes two arguments : the name of the file and the method of opening it.

The possible methods of the FileMode paramenter are :

  • Append - opens an exisiting or creates a new file if it is not found
  • Create - creates a new file, deleting an existing file of the same name, if it exists.
  • CreateNew - creates a new file but does not delete it if it already exists.
  • Open - opens an existing file.
  • OpenOrCreate - opens an existing file and creates it if it does not exist.
  • Truncate - opens an existing file and deletes the contents.

Note how the BinaryWriter class is used to Write the data to the file and the BinaryRead data is used to Read the data from the file.

The process of writing to a file is not difficult but the process of reading the data back could become complicated because you have to read the data into the correct datatypes.

The examples above do not include exception handling which should be used to check if the file was created and checking of datatypes when the data is read into the variables.