Text File Append
In this chapter you will learn:
Append to text file
File.AppendAllText
Opens a file, appends the specified string to the file.
It creates the file if it does not exist.
using System;/* j av a 2s . c o m*/
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
string path = @"c:\data.txt";
if (!File.Exists(path))
{
string createText = "Hello " + Environment.NewLine;
File.WriteAllText(path, createText);
}
string appendText = "extra text" + Environment.NewLine;
File.AppendAllText(path, appendText);
string readText = File.ReadAllText(path);
Console.WriteLine(readText);
}
}
Append file with StreamWriter
File.AppendText
Creates a StreamWriter
that appends UTF-8 encoded text to an existing file.
using System;/*from ja v a2 s .c om*/
using System.IO;
class Test
{
public static void Main()
{
string path = @"c:\temp\MyTest.txt";
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Hello");
sw.WriteLine("And");
sw.WriteLine("Welcome");
}
}
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine("This");
sw.WriteLine("is Extra");
sw.WriteLine("Text");
}
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
}
Next chapter...
What you will learn in the next chapter: