tags:

views:

149

answers:

3

Dear all,

My below code create a txt file and write something to that file.but i need to write new line after the previous lines when i run the script several times. code:

            string filePath = "D:\\DOT_NET\\C#\\abc.txt";
            FileInfo t = new FileInfo(filePath);
            StreamWriter Tex = t.CreateText();
            Tex.WriteLine("Hi freinds");
            Tex.WriteLine("csharpfriends is the new url for c-sharp");
            Tex.Write(Tex.NewLine);
            Tex.Close();

current output on the abc.txt file: Hi friends
csharpfriends is the new url for c-sharp

but i need the output if i run the script several times.

Hi friends
csharpfriends is the new url for c-sharp

Hi friends
csharpfriends is the new url for c-sharp

Hi friends
csharpfriends is the new url for c-sharp

How can i do that?

Pls help

thanks Riad

+6  A: 

StreamWriter has a constructor which lets you append text instead of just writing into the file. The constructor is

new StreamWriter(string filepath, bool append)

If you set that bool to "true", then all writing will be at the end of the document. In your example...

StreamWriter Tex = new StreamWriter(@"D:\DOT_NET\C#\abc.txt", true);
ccomet
thanks for ans,but it will be better for me if you pls elaborate your ans.pls guide how can i add the constractor on my mentioned code..thanksriad
riad
@riad Replace your current StreamWriter Tex declaration with the one I wrote below. You don't have to change anything else since you still close it properly.
ccomet
What is there to elaborate? What *exactly* isn't clear in @ccomet's answer?
Wim Hollebrandse
thanks bro its working-riad
riad
I don't think ccomet is a 'bro'.
bobobobo
A: 

just work around to this add "\n" before line

for example :

 tw.Write("\nWhy Did the Chicken Cross the Road?");
Pranay Rana
The issue is that on multiple runs it doesn't append but create a new file.
Wim Hollebrandse
+2  A: 
using (StreamWriter sw = File.AppendText(path)) 
{
   sw.WriteLine("...");
}
Carlos Loth