我想打开一个文本文件,添加一行,然后关闭它。
当前回答
using (StreamWriter w = File.AppendText("myFile.txt"))
{
w.WriteLine("hello");
}
其他回答
你可以看看TextWriter类。
//Open File
TextWriter tw = new StreamWriter("file.txt");
//Write to file
tw.WriteLine("test info");
//Close File
tw.Close();
using (StreamWriter w = File.AppendText("myFile.txt"))
{
w.WriteLine("hello");
}
您可以使用File。它的AppendAllText:
File.AppendAllText(@"c:\path\file.txt", "text content" + Environment.NewLine);
文件。AppendText会这样做:
using (StreamWriter w = File.AppendText("textFile.txt"))
{
w.WriteLine ("-------HURRAY----------");
w.Flush();
}
选择一个!但第一个非常简单。最后一个可能是用于文件操作的util:
//Method 1 (I like this)
File.AppendAllLines(
"FileAppendAllLines.txt",
new string[] { "line1", "line2", "line3" });
//Method 2
File.AppendAllText(
"FileAppendAllText.txt",
"line1" + Environment.NewLine +
"line2" + Environment.NewLine +
"line3" + Environment.NewLine);
//Method 3
using (StreamWriter stream = File.AppendText("FileAppendText.txt"))
{
stream.WriteLine("line1");
stream.WriteLine("line2");
stream.WriteLine("line3");
}
//Method 4
using (StreamWriter stream = new StreamWriter("StreamWriter.txt", true))
{
stream.WriteLine("line1");
stream.WriteLine("line2");
stream.WriteLine("line3");
}
//Method 5
using (StreamWriter stream = new FileInfo("FileInfo.txt").AppendText())
{
stream.WriteLine("line1");
stream.WriteLine("line2");
stream.WriteLine("line3");
}