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.

Advertisement

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

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

  1. Gregory says:

    How would you handle to write to a record to a file from different methods, I do not want to open and close a file every a time I want to write a record. The idea is to open the file once when starting the program and then write a record to a file then after program is done close the file. Thanks

  2. Pete Kane says:

    Use a TextWriter open it at the start and close when finished

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 )

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: