5 ways to write to a file with C# .NET

It’s a common scenario that you need to write some content to a file. Here you see 5 ways to achieve that.

1. Using a FileStream:

private void WriteToAFileWithFileStream()
{
	using (FileStream target = File.Create(@"c:\mydirectory\target.txt"))
	{
		using (StreamWriter writer = new StreamWriter(target))
		{
			writer.WriteLine("Hello world");
		}
	}
}

This will create a new file or overwrite an existing one.

Write and WriteLine have asynchronous versions as well: WriteAsync and WriteLineAsync. If you don’t know how to use async methods that return a Task then start here.

The following variation will append the text to an existing file or create a new one:

using (FileStream target = File.Open(@"c:\mydirectory\target2.txt", FileMode.Append, FileAccess.Write))
{
	using (StreamWriter writer = new StreamWriter(target))
	{
		writer.WriteLine("Hello world");
	}
}

2. Using a StreamWriter directly – to be used for text files:

private static void WriteToAFileWithStreamWriter()
{
	using (StreamWriter writer = File.CreateText(@"c:\mydirectory\target.txt"))
	{
		writer.WriteLine("Bye world");
	}
}

This will create a new file or overwrite an existing one.

The following variation will append the text to an existing file or create a new one:

using (StreamWriter writer = File.AppendText(@"c:\mydirectory\target.txt"))
{
	writer.WriteLine("Bye world");
}

3. Using File:

private static void WriteToAFileWithFile()
{
	File.WriteAllText(@"c:\mydirectory\target.txt", "Hello again World");
}

There’s File.WriteAllBytes as well if you have the contents as a byte array. There’s also a File.AppendAllText method to append to an existing file or create a new one if it doesn’t exist.

4. Using a MemoryStream first:

private static void WriteToAFileFromMemoryStream()
{
	using (MemoryStream memory = new MemoryStream())
	{
		using (StreamWriter writer = new StreamWriter(memory))
		{
			writer.WriteLine("Hello world from memory");
			writer.Flush();
			using (FileStream fileStream = File.Create(@"c:\mydirectory\memory.txt"))
			{
				memory.WriteTo(fileStream);
			}
		}
	}
}

5. Using a BufferedStream:

private static void WriteToAFileFromBufferedStream()
{
	using (FileStream fileStream = File.Create(@"c:\mydirectory\buffered.txt"))
	{
		using (BufferedStream buffered = new BufferedStream(fileStream))
		{
			using (StreamWriter writer = new StreamWriter(buffered))
			{
				writer.WriteLine("Hello from buffered.");
			}
		}
	}
}

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

You are commenting using your Google+ 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

HarsH ReaLiTy

My goal with this blog is to offend everyone in the world at least once with my words… so no one has a reason to have a heightened sense of themselves. We are all ignorant, we are all found wanting, we are all bad people sometimes.

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

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: