c# read file code example

Example 1: c sharp how to read a text file

// To save the text as one string use 'ReadAllText()'
string text = System.IO.File.ReadAllText(@"C:\filepath\file.txt");
// To save each line seperately in an array use 'ReadAllLines()'
string[] lines = System.IO.File.ReadAllLines(@"C:\filepath\file.txt");

Example 2: read file c#

string text = File.ReadAllText(@"c:\file.txt", Encoding.UTF8);

Example 3: c# read all text from a file

using (StreamReader streamReader = new StreamReader(path_name, Encoding.UTF8))
{
  contents = streamReader.ReadToEnd();
}

Example 4: c# read file stream

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

namespace StreamReaderReadToEnd
{
    class Program
    {
        static void Main(string[] args)
        {
            var path = @"C:\Users\Jano\Documents\thermopylae.txt";

            using var fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            using var sr = new StreamReader(fs, Encoding.UTF8);
            
            string content = sr.ReadToEnd();

            Console.WriteLine(content);
        }
    }
}

Example 5: c# read file store in String

using System;
using System.IO;
 
public class Example
{
    public static void Main()
    {
        string fileName = @"C:\some\path\file.txt";
 
        string text = File.ReadAllText(fileName);
        Console.WriteLine(text);
    }
}

Example 6: how to read a text file C#

string[] text = System.IO.File.ReadAllLines(@"C:\users\username\filepath\file.txt");