You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

创建文件后写入抛出IOException:文件正被另一进程占用

解决File.WriteAllLines抛出“文件正被另一进程占用”的问题

问题原因

File.Create()方法创建文件后,会返回一个未关闭的FileStream对象,这个流会持续锁定文件,直到被显式关闭或释放。此时调用File.WriteAllLines()访问同一文件,就会因文件被当前进程占用而抛出IOException。

解决方案

有两种可靠的解决方式:

方式1:移除多余的File.Create调用

File.WriteAllLines()本身支持文件不存在时自动创建,完全不需要提前用File.Create()初始化文件。修改后的代码如下:

Directory.CreateDirectory(tempShiftPath);

string[] infoContents =
{
    Convert.ToString(shift.TimeFrame.Start) + ";" + Convert.ToString(shift.TimeFrame.End),
    shift.Description
};
File.WriteAllLines(tempShiftPath + "Info.shift", infoContents);
// 后续写入Legs.shift时,同样直接使用WriteAllLines或其他写入方法即可
return shift;

方式2:显式关闭File.Create返回的流

如果确实需要提前创建文件,必须用using语句自动释放流资源(推荐),或者手动调用Close()方法:

Directory.CreateDirectory(tempShiftPath);
// 使用using语句,代码块结束后自动关闭流并释放文件锁
using (File.Create(tempShiftPath + "Info.shift")) {}
using (File.Create(tempShiftPath + "Legs.shift")) {}

string[] infoContents =
{
    Convert.ToString(shift.TimeFrame.Start) + ";" + Convert.ToString(shift.TimeFrame.End),
    shift.Description
};
File.WriteAllLines(tempShiftPath + "Info.shift", infoContents);
return shift;

补充说明

之前代码偶然能运行,可能是因为垃圾回收(GC)意外回收了未关闭的流,但这种情况完全不可控。显式管理流资源或直接使用更简洁的写入方法,才是稳定的解决方案。

内容的提问来源于stack exchange,提问作者Cryfox01

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 10:40:59