StreamWriter在创建文件后崩溃

use*_*794 -1 c# file-io

所以我有我的写入文件功能,它将创建该文件,如果它不存在,它的工作但问题是你第一次运行代码时文件不存在它创建它然后崩溃程序

//writing file to Error.txt
string path = @err;
if (!File.Exists(path)) // if does not exist make it 
{
    File.Create(path);
    TextWriter tw = new StreamWriter(path); //crashes here after create
    tw.WriteLine(i);
    tw.Close();
}
Run Code Online (Sandbox Code Playgroud)

例外情况是:

mscorlib.dll中发生了未处理的"System.IO.IOException"类型异常

附加信息:进程无法访问文件
'C:\ Users\Desktop\TestStuff\error.txt',因为它正由另一个进程使用.

Sam*_*ica 7

你在这里使用了2个文件流而没有关闭第一个文件流.

摆脱File.Create(path);.该方法创建一个文件,但它也返回一个您不存储和关闭的文件流.

StreamWriter 会为你制作文件,但它不能,因为你的程序有一个句柄.