sachin kulkarni
sachin kulkarni

Reputation: 2848

Append a txt file in .Net

I am Creating a txt file in.Net with the help of below code.

StreamWriter writerVer = new StreamWriter(@"c:\Version.txt");                    
writerVer.WriteLine("Version : " + Context.Parameters["ver"]);                  
File.SetAttributes(@"C:\Version.txt", FileAttributes.Hidden);

Then I need to Update the file on the next line by keeping the above code as it is.

This code overrites the entire file.

StreamWriter writer = new StreamWriter(@"c:\Version.txt");
writer.WriteLine("Connection string : "+con);

Regrads,

Sachin K

Upvotes: 0

Views: 268

Answers (3)

RobV
RobV

Reputation: 28675

Use the constructor which takes the append boolean parameter to indicate whether to append to the file - http://msdn.microsoft.com/en-us/library/36b035cb.aspx

StreamWriter writer = new StreamWriter("file.txt", true);

Upvotes: 4

Adam Houldsworth
Adam Houldsworth

Reputation: 64527

Alternatively, you could use the static helper methods: File.AppendAllText or File.AppendText.

Note that the latter actually returns a StreamWriter instance, so you'll need to close it before proceeding otherwise you're relying on the GC to do it for you.

Upvotes: 3

Øyvind Bråthen
Øyvind Bråthen

Reputation: 60744

try this

 StreamWriter writerVer = new StreamWriter(@"c:\Version.txt", true);

There is an overload of the StreamWriter constructor that takes an additional bool parameter to indicate if you want to append or not.

Upvotes: 4

Related Questions