C#: Read or Write a File in One Line

If buffering and streaming performance aren’t required, here are six examples on how to use System.IO.File to read/write strings, string arrays, and byte arrays from/to a file in just one line without having to loop through blocks or worrying about closing or disposing:

using System.IO;
const string inputFilename = @"c:\foo.dat";
string inString = File.ReadAllText(inputFilename);
string[] inArray = File.ReadAllLines(inputFilename);
byte[] bytes = File.ReadAllBytes(inputFilename);

const string outputFilename = @"c:\bar.dat";
File.WriteAllText(outputFilename, inString);
File.WriteAllLines(outputFilename, inArray);
File.WriteAllBytes(outputFilename, bytes);

If you need thread-safety, then you would have to add your own locking (typically ReaderWriterLockSlim). You probably won’t be using unbuffered filename-based I/O that much in production code, but it comes in handy for examples and ad-hoc utilities.

Leave a Comment