4 ways to read the contents of a file with C# .NET

.NET supports a number of ways to read from a file. Here come 4 of them.

1. Using FileStream:

private void ReadFileWithFileStream()
{
	using (FileStream fileStream = File.Open(@"c:\mydirectory\source.txt", FileMode.Open, FileAccess.Read))
	{
		using (StreamReader streamReader = new StreamReader(fileStream))
		{
			Console.Write(streamReader.ReadToEnd());
		}
	}
}

2. Using StreamReader:

private void ReadFileWithStreamReader()
{
	using (StreamReader reader = File.OpenText(@"c:\mydirectory\source.txt"))
	{
		Console.Write(reader.ReadToEnd());
	}
}

StreamReader.ReadToEnd has an awaitable version ReadToEndAsync which you can use to read from the file asynchronously. If you don’t know what this means then start here.

3. Using File:

private void ReadFileWithFile()
{
	Console.WriteLine(File.ReadAllText(@"c:\mydirectory\source.txt"));
}

4. Using BufferedStream:

private void ReadFileWithBufferedStream()
{
	using (FileStream fileStream = File.Open(@"c:\mydirectory\source.txt", FileMode.Open, FileAccess.Read))
	{
		using (BufferedStream bufferedStream = new BufferedStream(fileStream))
		{
			using (StreamReader streamReader = new StreamReader(bufferedStream))
			{
				Console.Write(streamReader.ReadToEnd());
			}
		}
	}
}

Read all posts dedicated to file I/O here.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: