Reading and writing data using System.IO.File

suggest change

AppendAllLines and WriteAllLines were added in .NET Framework 4. ReadAllText, ReadAllLines, ReadAllBytes, WriteAllText, WriteAllBytes, and AppendAllText are available in .NET Framework 2.0.

Three ways to read a file:

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

Three methods append data to a file. If the file does not exist, each method creates it before appending:

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.");
}

Three methods write data to a file. Writing overwrites the file; appending adds to it. If the file does not exist, each method creates it before writing:

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