The File class provides three methods to append an existing file.
string fileName = @"C:\Temp\Mahesh.txt";using (StreamWriter sw = File.AppendText(fileName)){ sw.WriteLine("--------- Append Text Start ----------"); sw.WriteLine("New author started"); sw.WriteLine("a book on Files Programming "); sw.WriteLine("using C#"); sw.WriteLine("--------- Append Text End ----------");}
The AppendAllText method opens a file, appends a specified string to the file and then closes the file. If the file does not exist, this method creates a new file, writes the specified string to the file, and then closes the file.
string fileName = @"C:\Temp\Mahesh.txt";string appendText = "Append all text method ----";File.AppendAllText(fileName, appendText);File.AppendAllText(fileName, "Append some more text");File.AppendAllText(fileName, "Append all text end"); // Read all textstring readText = File.ReadAllText(fileName);Console.WriteLine(readText); The AppendAllLines method appends lines to a file and then closes the file.// We can read a line from one file and write to other filestring fileName = @"C:\Temp\Mahesh.txt"; string[] lines = File.ReadAllLines(fileName); // Write all lines to a new filestring outputFileName = @"C:\temp\WriteLinesFile.txt";File.WriteAllLines(outputFileName, lines); // Append more linesstring[] moreLines = new string[]{"Line 1 goes here", "Line 2 goes here" };File.AppendAllLines(outputFileName, moreLines); // Read all textstring readText = File.ReadAllText(outputFileName);Console.WriteLine(readText);
You need to be a premium member to use this feature. To access it, you'll have to upgrade your membership.
Become a sharper developer and jumpstart your career.
$0
$
. 00
monthly
For Basic members:
$20
For Premium members:
$45
For Elite members: