进程无法访问该文件,因为它正由另一个进程 c# asp.net 使用

本文关键字:进程 另一个 asp 使用 net 因为 访问 文件 | 更新日期: 2023-09-27 18:35:45

我只是尝试使用 c# 创建一个文件并在其中写入。这是我的代码:

public void AddLog (string message, string fn_name)
{
    string path = @"E:'" + fn_name +".txt";
    if (!File.Exists(path))
    {
        File.Create(path);
        File.Delete(path);
        TextWriter tw = new StreamWriter(path);
        tw.WriteLine("" + message +"");
        tw.Close();
    }
    else if (File.Exists(path))
    {
        TextWriter tw = new StreamWriter(path,true);
        tw.WriteLine("" + message + "");
        tw.Close();
    }
}

问题是它总是给我这个例外:

{"进程无法访问文件'E:''CheckForFriends.txt,因为 它正被另一个进程使用。

在这一行:File.Delete(path);即使我删除了这一行,它也会在该行中给我相同的异常消息:File.Create(path);

那么,有人知道我的代码出了什么问题吗?

进程无法访问该文件,因为它正由另一个进程 c# asp.net 使用

使用一次性资源(实现 IDisposable 的东西)时,应使用 using 语句。

您可以简化为,如果文件不存在,StreamWriter 将创建该文件。

public void AddLog (string message, string fn_name)
{
    string path = @"E:'" + fn_name +".txt";
    using(var tw = new StreamWriter(path, true))
    {
      tw.WriteLine(message);
    }
}

这是因为您正在创建和打开一个文件,并尝试在它仍处于打开状态时将其删除:

      File.Create(path);
      File.Delete(path);

它应该只是

public void AddLog (string message, string fn_name)
    {
        string path = @"E:'" + fn_name +".txt";
        if (!File.Exists(path))
        {
            using (File.Create(path))
            using (TextWriter tw = new StreamWriter(path))
                tw.WriteLine("" + message +"");
        }
        else if (File.Exists(path))
        {
            using (TextWriter tw = new StreamWriter(path,true))
                tw.WriteLine("" + message + "");
        }
    }

我不确定,但是您在其他进程使用该文件时正在删除该文件:

尝试以下代码:

public void AddLog (string message, string fn_name)
    {
        string path = @"E:'" + fn_name +".txt";
        if (!File.Exists(path))
        {
            File.Create(path);
            TextWriter tw = new StreamWriter(path);
            tw.WriteLine("" + message +"");
            tw.Close();
            File.Delete(path);
        }
        else if (File.Exists(path))
        {
            TextWriter tw = new StreamWriter(path,true);
            tw.WriteLine("" + message + "");
            tw.Close();
        }
    }