C# File AppendText

Description

File AppendText Creates a StreamWriter that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist.

Syntax

File.AppendText has the following syntax.


public static StreamWriter AppendText(
  string path
)

Parameters

File.AppendText has the following parameters.

  • path - The path to the file to append to.

Returns

File.AppendText method returns A stream writer that appends UTF-8 encoded text to the specified file or to a new file.

Example

The following example appends text to a file.


/*from   w  ww.j a va2 s.com*/

using System;
using System.IO;

class Test 
{
    public static void Main() 
    {
        string path = @"c:\temp\MyTest.txt";
        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 from ");
            sw.WriteLine("java2s.com");
        }  

        using (StreamReader sr = File.OpenText(path)) 
        {
            string s = "";
            while ((s = sr.ReadLine()) != null) 
            {
                Console.WriteLine(s);
            }
        }
    }
}




















Home »
  C# Tutorial »
    System.IO »




BinaryReader
BinaryWriter
Directory
DirectoryInfo
DriveInfo
File
FileInfo
FileStream
MemoryStream
Path
StreamReader
StreamWriter
StringReader
StringWriter