Reading from and writing to a text file is the basic operation required in any programing language.

And, Every language has multiple options to perform read-write operations using built-in system classes. In this article, we will explore the multiple ways, How to read file in C#.

.Net Classes for a Reading text file

  • StreamReader
  • FileStream
  • File

Diffrent Kinds of Readers and Writers in C#

How to read a text file in C# Using StreamReader

StreamReader is a helper class for reading characters from a Stream by converting bytes into characters using an encoded value. It can read strings (characters) from different Streams like FileStream, MemoryStream, etc.

Methods Available in StreamReader

  • Read
  • ReadToEnd
  • ReadBlock
  • ReadLine
  using var streamReader = new StreamReader(@"C:\DK\test.text.json");
            var charBuffer = new char[1024];
            while (streamReader.Read(charBuffer, 0, 200) > 0)
            {
                Console.Write(new string(charBuffer));
            }

            Console.ReadKey();

The Read method is used to reads a specified maximum of characters from the current stream into a buffer, beginning at the specified index.

The read method returns the number of characters that have been read, or 0 if at the end of the stream and no data was read. The number will be less than or equal to the count parameter, depending on whether the data is available within the stream.

      using var streamReader = new StreamReader(@"C:\DK\test.text.json");
            var text = streamReader.ReadToEnd();
            Console.WriteLine(text);

The ReadToEnd method will read the entire file and return the contents in the string variable. The simplest way of reading a file, however, it is not the optimal solution if the file size is big.

     using var streamReader = new StreamReader(@"C:\DK\test.text.json");
            var charBuffer = new char[1024];
            streamReader.ReadBlock(charBuffer, 0, 20);
            foreach (var c in charBuffer)
            {
                Console.Write(c);
            }

The ReadBlock is used for reading the block of contents from the text file by providing the start and end index in the file.

As seen in the above example. ReadBlock takes three parameters. The first is the array of characters; the second is the starting index, and the third is the last index.

 using var streamReader = new StreamReader(@"C:\DK\test.text.json");
            while (streamReader.Peek() >= 0)
            {
                Console.WriteLine(streamReader.ReadLine());
            }

            Console.ReadKey();

Read File in C# Line by Line using ReadLine Method

ReadLine() method reads a line of characters from the current stream and returns the data as a string. Returns the next line from the input stream, or null if the end of the input stream is reached.

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.ConstrainedExecution;

namespace Demo.App
{
    static class Program
    {
        static void Main(string[] args)
        {
            using var streamReader = new StreamReader(@"C:\DK\test.text.json");
            string nextLine;
            while ((nextLine = streamReader.ReadLine()) != null)
            {
                Console.WriteLine(nextLine);
            }

            Console.ReadKey();
        }

    }
}

Output

Read File in C#
Read file line by line

How to Read and Write text files in C# using FileStream

StreamReader can be used for reading the stream from files, networks, and pipe clients & many more. However, FileStream class is provided specifically for reading and writing bytes into the physical file.

Methods Available in FileStream for Reading and Writing

  • Read()
  • ReadByte()
  • Write()
  • WriteByte()

We have already discussed, how to use the Read() and ReadByte() methods in the StreamReader. In FileStream as well it works in the same way.

While creating the instance of FileStream we need to specify the FileMode type. These are the different enum values supported in FileMode.

  • CreateNew: Creates a new file. An exception is raised if the file already exists.
  • Create: Creates a new file. If the file already exists, it is overwritten.
  • Open: Opens an existing file. An exception is raised if the file does not exist.
  • OpenOrCreate: Opens the file if it exists. Otherwise, it creates a new file.
  • Truncate: Opens an existing file. Once opened, the file is truncated so that its size is zero bytes. The calling process must open the file with at least WRITE access. An exception is raised if the file does not exist.
  • Append: Opens the file if it exists and seeks the end. Otherwise, it creates a new file.
            using var fileStream = new FileStream(@"C:\DK\test.text.json", FileMode.Open);
            var input = Console.ReadLine();
            if (input == null) return;
            var bytes = System.Text.Encoding.UTF8.GetBytes(input);
            fileStream.Write(bytes, 0, bytes.Length);

The code above will write the provided strings to the file. When we use FileMode.Open, the existing data in the file is always overwritten.

using var fileStream = new FileStream(@"C:\DK\test.text.json", FileMode.Append);

If we want to append data to the file while writing, we can use “File.Append.”

using var fileStream = new FileStream(@"C:\DK\" + Guid.NewGuid().ToString() + ".txt", FileMode.OpenOrCreate);

FileMode.OpenOrCreate can be used to open an existing file or create a new one if it does not exist.

  using var fileStream = new FileStream(@"C:\DK\" + Guid.NewGuid().ToString() + ".txt", FileMode.OpenOrCreate);
            var input = Console.ReadLine();
            if (input == null) return;
            var bytes = System.Text.Encoding.UTF8.GetBytes(input);
            foreach (var b in bytes)
            {
                fileStream.WriteByte(b);
            }

The WriteByte() method is used for writing each byte into the file.

using System;
using System.IO;

namespace Demo.App
{
    class Program
    {
        static void Main(string[] args)
        {
            var readLines = File.ReadLines(@"C:\DK\test.text.json");
            var readAllLines = File.ReadAllLines(@"C:\DK\test.text.json");
            var readAllText = File.ReadAllText(@"C:\DK\test.text.json");
        }

    }
}


File class from System.IO can be used for performing some basic file management operations.

Conclusion

By reading this article you will understand the different ways of reading text files in C# using StreamReader and FileStream classes.

Also, We have seen the helper class File, Which can be used to perform some basic operations related to files.

74 / 100

1 Comment