c# - 进程无法访问文件,因为它被 mscorlib.dll 使用

标签 c#

我写了一个 .dll 文件来创建扩展名为 csv 的日志文件。问题是,无论何时需要创建路径(因为它不存在),它都无法访问文件以在其中写入内容

void InitializePathDirectory(string dir)
{
    if (!Directory.Exists(dir))
    {
        Directory.CreateDirectory(dir);
    }
}

void InitializeFileDirectory(string file)
{
    if (!File.Exists(file))
    {
        File.Create(file);
    }
}

这里的路径是

private string dirname = $"{path}\\Logs";
private string filename = $"{path}\\Logs\\{DateTime.Now.ToString("dd.MM.yyyy")}.csv";

当我关闭一个使用这个 dll 的应用程序时,它通常会写入我的时间 将应用程序关闭到日志文件中

public void onExit()
{
    //var a is the DateTime, when the application starts
    var b = DateTime.Now;

    string temp = Convert.ToString(b - a);
    string[] time = temp.Split('.');

    File.AppendAllText(filename, $"Time:; {time[0]}\n");
    File.AppendAllText(filename, $"Starttime:; {a.ToString("HH:mm:ss")}\n");
    File.AppendAllText(filename, $"Endtime:; {b.ToString("HH:mm:ss")}\n\n");
}

但是如果日志文件路径是在同一次运行中创建的,我就不能向文件中写入任何内容,它会抛出一个异常,“mscorlib.dll”当前正在使用日志文件,所以我无法访问它

最佳答案

使用 File.Create()返回一个文件流,它允许您读/写新创建的文件。如果不处理/关闭此流,它将导致文件保持打开状态,从而阻止您随后调用 File.AppendAllText()

你有 2 3 方法来处理:

  1. 将调用包含在 using block 中:using (File.Create(filename)) {}
  2. 在文件流上手动调用处置:File.Create(filename).Dispose();
  3. 根本不要使用 File.Create()File.AppendAllText()方法已经检查文件是否存在,如果不存在将创建它,因此 File.Create() 完全多余且没有必要:

    Opens a file, appends the specified string to the file, and then closes the file. If the file does not exist, this method creates a file, writes the specified string to the file, then closes the file.

最后,作为 @Tofik在现已删除的答案中指出,您对 Directory.Exists(dir) 的调用也是多余的。请参阅 Directory.CreateDirectory(dir) 的文档:

Creates all directories and subdirectories in the specified path unless they already exist.

关于c# - 进程无法访问文件,因为它被 mscorlib.dll 使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52890100/

相关文章:

c# - 来自 C# 的 Runas/NETONLY

c# - 为什么在检查对象是否等于 null 之前先转换为 null?

c# - 依赖注入(inject)的学习原理,适用于这种情况?

c# - 如何从 c# Unity 中的另一个脚本扩展类

C#/MEF 不适用于没有无参数构造函数的基类

c# - 控制台应用程序代码错误

c# - 结构和类中的相等运算符重载

C# 最长常用词示例

c# - (obj != null) 不起作用

c# - .NETCF 异步 TCP 套接字正常关闭问题