5 ways to write to a file with C# .NET
January 21, 2015 2 Comments
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.
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
Use a TextWriter open it at the start and close when finished