How to Append a file in C#
By FoxLearn 2/14/2025 8:13:02 AM 533
Appending data to a file in C# can be done using various methods provided by the .NET framework.
Below are three common ways to append text to a file in C#:
Using StreamWriter
with append
parameter
string fileName = "c://demo.txt"; string line1 = "Welcome to FoxLearn."; string line2 = "This is the text to append."; using (StreamWriter sw = new StreamWriter(fileName, true)) { // c# add line to file sw.WriteLine(line1); sw.WriteLine(line2); }
Using File.AppendAllText
string fileName = "c://demo.txt"; string textToAppend = "Welcome to FoxLearn."; // c# write to file append File.AppendAllText(fileName, textToAppend + Environment.NewLine);
Using File.AppendText
string fileName = "c://demo.txt"; string line1 = "Welcome to FoxLearn."; string line2 = "This is the text to append."; // c# write text file append using (StreamWriter sw = File.AppendText(fileName)) { // c# add line to file sw.WriteLine(line1); sw.WriteLine(line2); }
You can also use FileInfo
class to help you append text to a file
string fileName = @"C:/fileName.txt"; FileInfo fi = new FileInfo(fileName); using (StreamWriter sw = fi.AppendText()) { // c# add line to file sw.WriteLine("C# Programming"); sw.WriteLine("Welcome to FoxLearn"); } // Read all text string readText = File.ReadAllText(fileName);
In these example:
- StreamWriter: Creates a
StreamWriter
object to write text to the file. The second parameter in the constructor (true
) specifies that the text should be appended to the file if it exists. - File.AppendAllText: A static method from the
File
class that appends the specified text to the file. - File.AppendText: Returns a
StreamWriter
object to append text to the file.
You can choose the method that best fits your needs based on your familiarity with the classes and your specific use case.
Categories
Popular Posts
Stisla Admin Dashboard Template
11/18/2024
Admin Tailwind CSS Admin Dashboard Template
11/18/2024
Portal HTML Bootstrap
11/14/2024