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
2010-05-14 19:33:16
+1
A:
using (StreamWriter w = File.AppendText("myFile.txt"))
{
w.WriteLine("hello");
w.Flush();
w.Close();
}
gmcalab
2010-05-14 19:33:38
you don't need the close if you have a using block.
Femaref
2010-05-14 19:34:39
nor the flush...
fearofawhackplanet
2010-05-14 19:49:10
A:
using (StreamWriter w = new StreamWriter(path))
{
w.WriteLine(line);
}
Femaref
2010-05-14 19:33:54
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
2010-05-14 19:43:22
+3
A:
You can use File.AppendAllText
for that:
File.AppendAllText(@"c:\path\file.txt", "text content" + Environment.NewLine);
Fredrik Mörk
2010-05-14 19:34:05
A:
File.AppendText will do it:
using (StreamWriter w = File.AppendText("textFile.txt"))
{
w.WriteLine ("-------HURRAY----------");
w.Flush();
}
David Relihan
2010-05-14 19:34:21