C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Step 1: Here we open the file for reading. We use StreamReader in a "using" block—this allows automatic cleanup of resources.
UsingStep 2: We call ReadLine. This is a method on StreamReader. It returns null if no further data is available in the file.
ReadLine, ReadLineAsyncStep 3: Here we have the line variable. This contains a line of the file (with no newlines included).
C# program that uses StreamReader, ReadLine
using System;
using System.IO;
class Program
{
    static void Main()
    {
        // Step 1: open file for reading.
        using (StreamReader reader = new StreamReader(@"C:\programs\file.txt"))
        {
            // Step 2: call ReadLine until null.
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                // Step 3: do something with the line.
                Console.WriteLine($"LINE: {line}");
            }
        }
    }
}
Output
LINE: Hello my friend
LINE: Welcome to the Internet
LINE: Third line in file
C# program that uses StreamWriter
using System.IO;
class Program
{
    static void Main()
    {
        // Create or open file and write line to it.
        // ... If file exists, it contents are erased before writing.
        using (var writer = new StreamWriter(@"C:\programs\example.txt"))
        {
            writer.WriteLine("HELLO");
        }
    }
}
Tip: ReadAllText is the easiest way to put a file into a string. It is part of the System.IO namespace.
C# program that uses ReadAllText
using System;
using System.IO;
class Program
{
    static void Main()
    {
        string file = File.ReadAllText("C:\\file.txt");
        Console.WriteLine(file);
    }
}
C# program that uses ReadAllLines
using System.IO;
class Program
{
    static void Main()
    {
        // Read in every line in specified file.
        // ... This will store all lines in an array in memory.
        string[] lines = File.ReadAllLines("file.txt");
        foreach (string line in lines)
        {
            // Do something with the line.
            if (line.Length > 80)
            {
                // Important code.
            }
        }
    }
}
C# program that counts lines
using System.IO;
class Program
{
    static void Main()
    {
        // Another method of counting lines in a file.
        // ... This is not the most efficient way.
        // ... It counts empty lines.
        int lineCount = File.ReadAllLines("file.txt").Length;
    }
}
C# program that uses LINQ on file
using System.IO;
using System.Linq;
class Program
{
    static void Main()
    {
        // See if line exists in a file.
        // ... Use a query expression to count matching lines.
        // ... If one matches, the bool is set to true.
        bool exists = (from line in File.ReadAllLines("file.txt")
                       where line == "Some line match"
                       select line).Count() > 0;
    }
}
C# program that uses File.ReadLines, foreach loop
using System;
using System.IO;
class Program
{
    static void Main()
    {
        // Read lines in file 1-by-1.
        foreach (string line in File.ReadLines(@"C:\programs\file.txt"))
        {
            Console.WriteLine("LINE: {0}", line);
        }
    }
}
Output
LINE: Hello my friend
LINE: Welcome to the Internet
...
C# program that writes array to file
using System.IO;
class Program
{
    static void Main()
    {
        // Write a string array to a file.
        string[] stringArray = new string[]
        {
            "cat",
            "dog",
            "arrow"
        };
        File.WriteAllLines("file.txt", stringArray);
    }
}
Output
cat
dog
arrow
Note: The file is created if it does not exist, or replaced with a new file if it does exist (no appends ever occur).
C# program that uses WriteAllText
using System.IO;
class Program
{
    static void Main()
    {
        File.WriteAllText("C:\\Codex.txt", "The Dev Codes");
    }
}
Argument 1: The first argument to File.AppendAllText is the name of the file we wish to append text to.
Argument 2: The second argument is the string we wish to append to the file—we must add a newline at the end if we want to write a line.
Internals: Inspected in IL Disassembler: AppendAllText internally calls StreamWriter, with the second parameter "append" set to true.
Note: If the file already exists when the program starts, the file will be appended to. Otherwise, a new file is created.
C# program that uses File.AppendAllText
using System.IO;
class Program
{
    static void Main()
    {
        // Use AppendAllText to write one line to the text file.
        File.AppendAllText("C:\\Codex.txt", "first part\n");
        // The file now has a newline at the end, so write another line.
        File.AppendAllText("C:\\Codex.txt", "second part\n");
        // Write a third line.
        string third = "third part\n";
        File.AppendAllText("C:\\Codex.txt", third);
    }
}
Output
first part
second part
third part
Output (repeat run):
first part
second part
third part
first part
second part
third part
C# program that caches binary file
static class ImageCache
{
    static byte[] _logoBytes;
    public static byte[] Logo
    {
        get
        {
            // Returns logo image bytes.
            if (_logoBytes == null)
            {
                _logoBytes = File.ReadAllBytes("Logo.png");
            }
            return _logoBytes;
        }
    }
}Version 1: In this version of the code, we read in the file with StreamReader line-by-line.
Version 2: Here we read in the file with File.ReadAllLines. The code is more complex and longer.
Result: Using ReadLine with StreamReader is faster. For files with many lines, it is worth reading in the lines iteratively.
C# program that benchmarks reading by lines
using System;
using System.Diagnostics;
using System.IO;
class Program
{
    static void CreateFileWithManyLines()
    {
        // Create temporary file for benchmark.
        using (StreamWriter writer = new StreamWriter(@"C:\programs\file.txt"))
        {
            for (int i = 0; i < 1000000; i++)
            {
                writer.WriteLine("x");
            }
        }
    }
    const int _max = 10;
    static void Main()
    {
        CreateFileWithManyLines();
        // Version 1: use StreamReader and read in each line.
        var s1 = Stopwatch.StartNew();
        for (int i = 0; i < _max; i++)
        {
            if (Method1() == 0)
            {
                return;
            }
        }
        s1.Stop();
        // Version 2: use File.ReadAllLines to get entire string array.
        var s2 = Stopwatch.StartNew();
        for (int i = 0; i < _max; i++)
        {
            if (Method2() == 0)
            {
                return;
            }
        }
        s2.Stop();
        Console.WriteLine( s1.Elapsed.TotalMilliseconds.ToString("0.00 ms"));
        Console.WriteLine( s2.Elapsed.TotalMilliseconds.ToString("0.00 ms"));
    }
    static int Method1()
    {
        int count = 0;
        using (StreamReader reader = new StreamReader(@"C:\programs\file.txt"))
        {
            while (true)
            {
                string line = reader.ReadLine();
                if (line == null)
                {
                    break;
                }
                count++;
            }
        }
        return count;
    }
    static int Method2()
    {
        string[] array = File.ReadAllLines(@"C:\programs\file.txt");
        return array.Length;
    }
}
Output
219.53 ms     StreamReader, ReadLine
1212.43 ms    File.ReadAllLinesSeek: We can seek to a specific location in a file with the Seek method. Seek is useful with large binary files.
SeekQuote: One of the most significant sources of inefficiency is unnecessary input/output (I/O) (Code Complete).
Quote: We can build small and fast storage, or large and slow storage, but not storage that is both large and fast (Compilers: Principles, Techniques and Tools).