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

C#创建TXT文件报错:文件被另一进程占用问题求助

解决C#创建文件后写入时提示被占用的问题

你遇到的错误是因为调用File.Create(path)后,该方法返回的FileStream对象没有被关闭,导致文件当前被你的程序自己占用,后续StreamWriter无法打开写入。

方案1:直接使用StreamWriter创建并写入(推荐)

StreamWriter的构造函数在指定文件不存在时,会自动创建文件,不需要提前调用File.Create。修改代码如下:

string path = @$"c:\Users\asmet\Desktop\Database1/{username}";

if (!File.Exists(path))
{
    Console.WriteLine("Creating new file..");
    // 直接用StreamWriter,文件不存在会自动创建,using块会自动关闭流
    using (StreamWriter sw = new StreamWriter(path, true)) 
    {
        sw.WriteLine(DateTime.Now);
        sw.WriteLine($"rf = {rf}");
        sw.WriteLine($"pf = {pf}");
        sw.WriteLine($"sf = {sf}");
        // 不需要手动调用sw.Close(),using块结束时会自动释放资源
    }
}

注意:using语句块会自动处理StreamWriter的资源释放,包括关闭文件流,所以不需要手动调用sw.Close()。

方案2:正确处理File.Create返回的流

如果一定要保留File.Create的调用,需要关闭它返回的FileStream:

string path = @$"c:\Users\asmet\Desktop\Database1/{username}";

if (!File.Exists(path))
{
    Console.WriteLine("Creating new file..");
    // 捕获File.Create返回的流,并关闭它
    using (FileStream fs = File.Create(path))
    {
        // 这里可以做一些文件创建后的操作,不需要的话直接空块即可
    }
          
    using (StreamWriter sw = new StreamWriter(path, true)) 
    {
        sw.WriteLine(DateTime.Now);
        sw.WriteLine($"rf = {rf}");
        sw.WriteLine($"pf = {pf}");
        sw.WriteLine($"sf = {sf}");
    }
}

额外提示

  • 路径规范:C#中路径建议统一用\(配合@符号避免转义),比如@$"c:\Users\asmet\Desktop\Database1\{username}",更符合Windows路径习惯。
  • 文件夹检查:如果Database1文件夹不存在,程序会抛出找不到路径的错误,建议提前判断并创建:
string folderPath = @"c:\Users\asmet\Desktop\Database1";
if (!Directory.Exists(folderPath))
{
    Directory.CreateDirectory(folderPath);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 02:25:44