tags:

views:

109

answers:

5

I want to open a text file, append a single line to it, then close it.

+1  A: 

Might want to check out the TextWriter class.

//Open File
TextWriter tw = new StreamWriter("file.txt");

//Write to file
tw.WriteLine("test info");

//Close File
tw.Close();
Robert Greiner
+1  A: 
using (StreamWriter w = File.AppendText("myFile.txt"))
{
  w.WriteLine("hello");
  w.Flush();
  w.Close();
}
gmcalab
you don't need the close if you have a using block.
Femaref
nor the flush...
fearofawhackplanet
A: 
using (StreamWriter w = new StreamWriter(path))
{
    w.WriteLine(line);
}
Femaref
I am pretty sure, this will overwrite the content of the file. StreamWriter should be initialized with StreamWriter(path, true), if appending is the indent.
tafa
+3  A: 

You can use File.AppendAllText for that:

File.AppendAllText(@"c:\path\file.txt", "text content" + Environment.NewLine);
Fredrik Mörk
A: 

File.AppendText will do it:

using (StreamWriter w = File.AppendText("textFile.txt")) 
{
    w.WriteLine ("-------HURRAY----------");
    w.Flush();
}
David Relihan