Text File Append

In this chapter you will learn:

  1. How to append to text file
  2. Append file with StreamWriter

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:

  1. How to replace the content of a text file
Home » C# Tutorial » Stream
Stream classes
Text File Read
Text File write
Text File Create
Text File Append
Replace File Content
BinaryReader
BinaryWriter
FileStream Create
FileStream byte read and write
BufferedStream
Compare File
File Copy
File Copy with FileStream
MemoryStream
Object Serialization
String Writer