这是我的代码
if (!File.Exists(pathName))
{
File.Create(pathName);
}
StreamWriter outputFile = new StreamWriter(pathName,true);
但是每当我第一次运行程序时,都会创建带有文件的路径。但是,一旦我到达 StreamWriter 行,我的程序就会崩溃,因为它说我的 fie 正在被另一个进程使用。 File.Create 和 StreamWriter 语句之间是否缺少某些内容?
最佳答案
File.Create不只是创建文件——它还会打开文件进行读写。因此,当您尝试通过自己的进程创建 StreamWriter: 时,该文件确实已经在使用中。
StreamWriter将创建由 pathName
指定的文件(如果它不存在),因此您可以简单地删除 File.Exists
检查并简化您的代码:
using (var writer = new StreamWriter(pathName, true))
{
// ...
}
来自 MSDN :
StreamWriter Constructor (Stream)
Initializes a new instance of the StreamWriter class for the specified file [...]. If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file.
关于c# - 尝试使用最近创建的文件后程序崩溃。 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2914147/