Click here to Skip to main content
14,494,016 members
Rate this:
Please Sign up or sign in to vote.
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.

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
Rate this:
Please Sign up or sign in to vote.

Solution 1

This will be appended to the existing file.

// 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[^]
   
Rate this:
Please Sign up or sign in to vote.

Solution 2

Sounds like you need to append text
see here[^]

and here[^]
   
Rate this:
Please Sign up or sign in to vote.

Solution 3

   
Rate this:
Please Sign up or sign in to vote.

Solution 4

In order to append an existing file, set the Boolean parameter to true, as follows:
System.IO.StreamWriter file =
   new System.IO.StreamWriter("YourFile", true);
   
v2

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100