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.

Advertisements

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 )

Google+ photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT BEST PRACTICES WITH MICROSOFT STACK & ANGULAR

Cyber Matters

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: