C# - 如何创建一个文本文件并向其添加一行文本?

C# - How to create a text file and add a line of text to it?

提问人:Ben Kisow 提问时间:6/9/2023 更新时间:6/9/2023 访问量:138

问:

我有一个创建文件的 C# 脚本,我想更新它以向文件添加一些文本。

这是完美用于创建文件的代码:

String filepath = "";
filepath = "This/is/a/dynamic/file/path.txt";

System.IO.File.Create(filepath);

我想添加一些代码来向文件添加一行文本。以下是我尝试过的,但是当我运行它时,我收到此错误:

错误:进程无法访问文件“This/is/a/dynamic/file/path.txt”,因为它正被另一个进程使用。

String filepath = "";
filepath = "This/is/a/dynamic/file/path.txt";

System.IO.File.Create(filepath);

System.IO.File.AppendAllText(filepath, "Text to add to file" + Environment.NewLine);

任何帮助将不胜感激,如果这是一个愚蠢的问题,请原谅我,因为我对 C# 非常陌生。

C# SSIS IO

评论

0赞 Vasya 6/9/2023
创建文件后需要关闭文件
1赞 quaabaam 6/9/2023
将 this, , 更改为 this, 。该文件仍由 Create 调用使用,您必须确保在尝试再次访问该文件之前将其关闭。无需在 AppendAllText 之后调用 Close,因为该方法将在追加文本后自动关闭文件。也就是说,这对于快速和肮脏的工作来说很好,但要正确处理文件,您应该查看 MS 文件信息System.IO.File.Create(filepath);System.IO.File.Create(filepath).Close();
0赞 Filburt 6/9/2023
这回答了你的问题吗?“System.IO.IOException:进程无法访问文件'C:\Test\test.txt',因为它正被另一个进程使用”

答:

0赞 Tarazed 6/9/2023 #1

当你使用它时,你会返回一个 which is ,你应该始终使用 using 语句来确保它被释放。这将确保它释放文件。File.CreateFileStreamIDisposable

using FileStream file = File.Create(filepath);

但是,如果文件不存在并且不返回 Stream,则将创建该文件,并在完成后关闭该文件,因此无需担心,只需一起删除 create 行即可。File.AppendAllText

https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltext?view=net-7.0

0赞 Adalyat Nazirov 6/9/2023 #2

如前所述,您在文件创建后立即错过了。.Close()

相反,我建议使用它来创建如果不存在,或写入现有文件。它还支持追加或覆盖模式StreamWriter

using (StreamWriter outputFile = new StreamWriter("This/is/a/dynamic/file/path.txt", true)))
{
   outputFile.WriteLine("Text to add to file");
}
0赞 Yashoja Lakmith 6/9/2023 #3

您的文件仍在被该方法使用(或保持打开状态)。因此,您需要在创建文件后将其关闭。File.Create()

File.Create(filepath).Close();
File.AppendAllText(filepath, "Your text\n");