Wednesday, June 17, 2026

C# File class for Reading files in different ways

File is static class in System.IO namespace. It provides a number of operations with file. These operations can be such as:

  1. Create
  2. Read
  3. Write
  4. Append
  5. Copy
  6. Delete
  7. Encrypt
  8. Decrypt
  9. Open
  10. Close
  11. Get Creation Time
  12. Get Last Access Time
  13. Get Last Write Time
  14. Get Attributes

How to Read file

File class provides various read methods to read a file. These read methods automatically open the file and when the read operation is done, the file is automatically closed. Developer don't have to explicitly call Open and Close methods for this. If you use File.Open method, object of FileStream is created. This resource must be closed when file operation(read,write or append) is done with the file stream object using File.Close method. The File.Open method should be done with caution to open a file; if the file is missing at the speciified path, exception is thrown that should be handled by developer, or developer should use File.Exists method to check if the file exists at the specified path.

Read files line by line

The File class provides following methods to read a file line by line. The file can be read asynchronously also. The following methods are used for reading a file line by line:

  1. ReadAllLines: It returns an array of string.
  2. ReadAllLinesAsync: It returns an array of string.
  3. ReadLines: It returns an IEnumerable< string>.

Using these methods,  files can be read for a specific line(s), upto a line or from a line to a specific line.

Example. File.ReadAllLines

class Demo
{
    static void Main()
    {
        var mydocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        string filepath = Path.Combine(mydocs, "test.txt");
        if (File.Exists(filepath))
        {
            string[] lines = File.ReadAllLines(filepath);
            Console.WriteLine("Line no. 1: " + lines[0]);
            Console.WriteLine("Line no. 3: " + lines[1]);
            Console.WriteLine("Last Line : " + lines[lines.Length - 1]);
        }
    }
}

Example. File.ReadAllLinesAsync

class Demo
{
    public static async Task Main()
    {
        var mydocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        string filepath = Path.Combine(mydocs, "test.txt");
        if (File.Exists(filepath))
        {
            await ReadFileAsynchronously(filepath);
        }
    }
    public static async Task ReadFileAsynchronously(string filepath)
    {
        string[] lines = await File.ReadAllLinesAsync(filepath);
        Console.WriteLine("Line no. 1: " + lines[0]);
        Console.WriteLine("Line no. 3: " + lines[1]);
        Console.WriteLine("Last Line : " + lines[lines.Length - 1]);
    }
}

Note: The Main is converted into async method with Task return type.

Example. File.ReadLines

class Demo
{
    static void Main()
    {
        var mydocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        string filepath = Path.Combine(mydocs, "test.txt");
        if (File.Exists(filepath))
        {
            // can read all lines, but cannot access using index
            IEnumerable<string> lines = File.ReadLines(filepath);
            foreach (var line in lines)
            {
                Console.WriteLine(line);
            }
        }
    }
}

Example. ReadAllText

This method is useful if you want to read all text of a file. The method returns string data in one go. You don’t need to enumerate file line by line. The ReadAllTextAsync is asynchronous method.

class Demo
{
    static void Main()
    {
        var mydocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        string filepath = Path.Combine(mydocs, "test.txt");
        if (File.Exists(filepath))
        {
            string text = File.ReadAllText(filepath);
            Console.WriteLine(text);
        }
    }
}

Example. ReadAllBytes: This method is useful if you want to read all bytes of a file. The method returns data as byte array. The byte array can be converted into string. You can read specific range of bytes also.

class Demo
{
    static void Main()
    {
        var mydocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        string filepath = Path.Combine(mydocs, "test.txt");
        if (File.Exists(filepath))
        {
            byte[] buffer = File.ReadAllBytes(filepath);
            string data = System.Text.Encoding.UTF8.GetString(buffer);
            Console.WriteLine(data);
        }
    }
}

NOTE: ReadAllBytesAsync is asynchronous version.

 

No comments:

Post a Comment

Hot Topics