Reading and writing data using System.IO.File
suggest changeAppendAllLines 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);
- The first line reads the whole file as a string.
- The second line reads the file into a string array. Each line in the file becomes an element.
- The third line reads the raw bytes.
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.");
}
- The first call adds a string to the end of the file.
- The second call writes each array element as its own line.
File.AppendTextopens aStreamWriterthat appends whatever is written to it.
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 });
- The first call writes a string to the file.
- The second call writes each string in the array on its own line.
- The third call writes a byte array.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents