c# - 尝试使用最近创建的文件后程序崩溃。 C#

标签 c# file-io streamwriter

这是我的代码

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/

相关文章:

c# - 将大文件写入磁盘内存不足异常

java - 从 xml 中存储的数据创建文件

c# - 如何使用 DataTemplate 从 ItemsControl 获取 UIElement?

C# 动态创建 Lambda 表达式

c# - 自动登录 Active Directory

c - 我的程序没有按预期工作

c# - 同一可执行文件中的 Wpf 和命令行应用程序

c - 如何以优化方式加载更大的文本文件到缓冲区--c程序

php - 将文件引用作为函数参数传递

go - io.Writer 的日志数据