我想打开一个文本文件,添加一行,然后关闭它。
当前回答
选择一个!但第一个非常简单。最后一个可能是用于文件操作的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");
}
其他回答
你可以看看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。AppendAllLines(字符串,IEnumerable <字符串>)
File.AppendAllLines(@"C:\Path\file.txt", new[] { "my text content" });
您可以使用File。它的AppendAllText:
File.AppendAllText(@"c:\path\file.txt", "text content" + Environment.NewLine);
技术上最好的方法可能是这样的:
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();
}
}
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 在c#代码中设置WPF文本框的背景颜色
- 如何在Python中获得所有直接子目录
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 即使模板文件存在,Flask也会引发TemplateNotFound错误
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何分裂()一个分隔字符串到一个列表<字符串>