我想打开一个文本文件,添加一行,然后关闭它。


当前回答

技术上最好的方法可能是这样的:

private static async Task AppendLineToFileAsync([NotNull] string path, string line)
{
    if (string.IsNullOrWhiteSpace(path)) 
        throw new ArgumentOutOfRangeException(nameof(path), path, "Was null or whitepsace.");

    if (!File.Exists(path)) 
        throw new FileNotFoundException("File not found.", nameof(path));

    using (var file = File.Open(path, FileMode.Append, FileAccess.Write))
    using (var writer = new StreamWriter(file))
    {
        await writer.WriteLineAsync(line);
        await writer.FlushAsync();
    }
}

其他回答

或者您可以使用File。AppendAllLines(字符串,IEnumerable <字符串>)

File.AppendAllLines(@"C:\Path\file.txt", new[] { "my text content" });

文件。AppendText会这样做:

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

技术上最好的方法可能是这样的:

private static async Task AppendLineToFileAsync([NotNull] string path, string line)
{
    if (string.IsNullOrWhiteSpace(path)) 
        throw new ArgumentOutOfRangeException(nameof(path), path, "Was null or whitepsace.");

    if (!File.Exists(path)) 
        throw new FileNotFoundException("File not found.", nameof(path));

    using (var file = File.Open(path, FileMode.Append, FileAccess.Write))
    using (var writer = new StreamWriter(file))
    {
        await writer.WriteLineAsync(line);
        await writer.FlushAsync();
    }
}

您可以使用File。它的AppendAllText:

File.AppendAllText(@"c:\path\file.txt", "text content" + Environment.NewLine);
//display sample reg form in notepad.txt
using (StreamWriter stream = new FileInfo("D:\\tt.txt").AppendText())//ur file location//.AppendText())
{
   stream.WriteLine("Name :" + textBox1.Text);//display textbox data in notepad
   stream.WriteLine("DOB : " + dateTimePicker1.Text);//display datepicker data in notepad
   stream.WriteLine("DEP:" + comboBox1.SelectedItem.ToString());
   stream.WriteLine("EXM :" + listBox1.SelectedItem.ToString());
}