Friday, February 13, 2009

C#: Reading and Writing Full File Content (text or binary)

To read all text:

string fileName = "c:\dir\somefile.txt";
string text = File.ReadAllText(fileName);

To write all text:

string fileName = "c:\dir\somefile.txt";
string text = "Here's some text...\r\nAnd some more in the next line...";
File.WriteAllText(fileName, text);


To read all bytes:

byte[] buffer = new byte[BIG_ENOUGH_SIZE];
string fileName = "somefile.bin";
// opens a binary file, reads bytes, then closes
buffer = File.ReadAllBytes(fileName);

To write all bytes:

// creates a new file (or overwrites, writes bytes, then closes
File.WriteAllBytes(filename, buffer);

No comments: