How to Read/Write Lines and Bytes in C#

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 string to the file and then closes the file.

// We can read a line from one file and write to other 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);

}


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[] byts = File.ReadAllBytes(fileName);

Up Next
    Ebook Download
    View all
    Learn
    View all