How To Read/Write Lines And Bytes In C#

How to Read and Write Lines?

The ReadAllLines method opens a text file, reads all lines of the file into a string array, and then closes the file. The ReadLines reads the lines of a file.

The WriteAllLines creates a new file, writes one or more strings to the file, and then closes the file.

// We can read a line from one file and write to another file

string fileName = @"C:\Temp\Mahesh.txt";
if (!File.Exists(fileName))
{
    string[] newLines = { "First Line ", "Second Line ", "Third Line " };
    File.WriteAllLines(fileName, newLines);
}
string appendText = "Append one more line. \n";
File.AppendAllText(fileName, appendText);
// Write all lines to a new file
string[] lines = File.ReadAllLines(fileName);
foreach (string line in lines)
{
    Console.WriteLine(line);
}

How to Read and Write Bytes?

The WriteAllBytes creates a new file, writes the specified byte array to the file, and then closes the file. If a file already exists, then this method overwrites it.

The ReadAllBytes method opens a binary file, reads the contents of the file into a byte array, and then closes the file.

string fileName = @"C:\Temp\Mahesh2.txt";
byte[] bytes = File.ReadAllBytes(fileName);


Similar Articles