Open a stream to append to a text file in CSharp

Description

The following code shows how to open a stream to append to a text file.

Example


//from   ww  w.  j  a  v a  2s .c  o  m
using System;
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);
            }
        }
    }
}




















Home »
  C# Tutorial »
    IO »




File Attribute
File Security
Directory Attribute
Directory Recursive
Binary File
Text Field
Buffered IO
Create Copy Delete Move
CSV
Drive
File System Watcher
Isolated Storage
MemoryStream
Serialize
Zip