ReadingWriting Data Using System.IO.File

suggest change

First, let’s see three different ways of extracting data from a file.

string fileText = File.ReadAllText(file);
string[] fileLines = File.ReadAllLines(file);
byte[] fileBytes = File.ReadAllBytes(file);

Next, let’s see three different methods of appending data to a file. If the file you specify doesn’t exist, each method will automatically create the file before attempting to append the data to it.

File.AppendAllText(file, "Here is some data that is\nappended to the file.");
File.AppendAllLines(file, new string[2] { "Here is some data that is", "appended to the file." });
using (StreamWriter stream = File.AppendText(file))
{
    stream.WriteLine("Here is some data that is");
    stream.Write("appended to the file.");
}

And lastly, let’s see three different methods of writing data to a file. The difference between appending and writing being that writing over-writes the data in the file while appending adds to the data in the file. If the file you specify doesn’t exist, each method will automatically create the file before attempting to write the data to it.

File.WriteAllText(file, "here is some data\nin this file.");
File.WriteAllLines(file, new string[2] { "here is some data", "in this file" });
File.WriteAllBytes(file, new byte[2] { 0, 255 });

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents