Click here to Skip to main content
15,914,452 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I need to write to an existing text file without overwriting the existing content.

Suppose the file sample.txt has following content

sample.txt:

visual c#
visual basic
asp.net
webservices

Now i want to write the same file below the content "webservices" as shown below

visual c#
visual basic
asp.net
webservices
dotnet
wcf webservice

when i tried to write using streamwriter class it overrides the existing content and updated the file with new data.Sample code is shown below.
Can anyone please help me reg this.

C#
string path = Path.Combine(outputpath, outputfile);
         fileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
         writer = new StreamWriter(fileStream, Encoding.UTF8);
         for (i = 0; i < dt.Columns.Count - 1; i++)
         {
             writer.Write(dt.Columns[i].ColumnName + ;);
         }
         writer.Write(dt.Columns[i].ColumnName + ;);
         writer.WriteLine(); /*For Data in the Rows*/

         foreach (DataRow row in dt.Rows)
         {
             object[] array = row.ItemArray;
             for (i = 0; i < array.Length - 1; i++)
             {
                 writer.Write(array[i].ToString() + ;);
             }
             writer.Write(array[i].ToString());
             writer.WriteLine();
         }
         writer.WriteLine("-------------------------------------------");
         writer.Flush();
         writer.Close();
Posted
Updated 26-Dec-11 1:49am
v2

This will be appended to the existing file.

C#
// This text is always added, making the file longer over time
using (StreamWriter sw = File.AppendText(path))
{
    sw.WriteLine("This");
    sw.WriteLine("is Extra");
    sw.WriteLine("Text");
}


Check the following for complete example:

http://msdn.microsoft.com/en-us/library/system.io.file.appendtext.aspx[^]
 
Share this answer
 
Sounds like you need to append text
see here[^]

and here[^]
 
Share this answer
 
 
Share this answer
 
In order to append an existing file, set the Boolean parameter to true, as follows:
C#
System.IO.StreamWriter file =
   new System.IO.StreamWriter("YourFile", true);
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900