C# 多次调用file.AppendAllLines并在Visual Studio中打开文件时出现间歇性文件锁定异常

C# 多次调用file.AppendAllLines并在Visual Studio中打开文件时出现间歇性文件锁定异常,c#,.net-core,C#,.net Core,我在通过反射调用的类上有许多方法: var instances = new TestsBase[] { new CompilerGeneratedTestData(), new ConstructedTestData(), new VBCompilerGeneratedTestData() }; var methods = instances .SelectMany(x => x.GetType() .GetMeth

我在通过反射调用的类上有许多方法:

var instances = new TestsBase[] {
    new CompilerGeneratedTestData(),
    new ConstructedTestData(),
    new VBCompilerGeneratedTestData()
};

var methods = instances
    .SelectMany(x =>
        x.GetType()
            .GetMethods()
            .Select(m => (instance: x, method: m))
    )
    .OrderBy(x => x.method.ReflectedType.Name)
    .ThenBy(x => x.method.Name)
    .ToList();
这些方法最终都会调用以下代码:

string[] toWrite = ...
var outfileName = @"c:\path\to\text.txt";
File.AppendAllLines(outfileName, toWrite);
当我运行代码时,在调用
File.AppendAllLines
时,在某个点上会出现以下异常:

System.IO.IOException:“该进程无法访问文件'c:\path\to\text.txt',因为它正被另一个进程使用。”

每次原始方法调用似乎都不同;它没有在某个特定的方法上失败

该应用程序是一个简单的控制台项目,代码中没有多线程

如何避免此错误?


我有一组带有XUnit测试方法的抽象类:

public class ConstructedBase {
    protected abstract void RunTest(object o, string csharp, string vb, string factoryMethods);

    [Fact]
    public void ConstructAdd() => RunTest(Expression.Add(x, y), "x + y", "x + y", "Add(x, y)");

    ...
}
以及定义
运行测试的实现的类:

class ConstructedTestData : ConstructedBase {
    protected override void RunTest(object o, string csharp, string vb, string factoryMethods) => Runner.WriteData(o, factoryMethods);
}
作为向
静态方法的转发:

public static class Runner {
    public static readonly string outfileName = @"c:\path\to\text.txt";
    public static void WriteData(object o, string testData) {
        string[] toWrite = ...
        File.AppendAllLines(outfileName, toWrite);
    }
}

更新


只有在Visual Studio中同时打开文本文件时,才会出现此错误。

问题可能是Visual Studio(或反病毒)正在锁定该文件

您应该在Visual Studio中关闭它。

有两种选择:

  • 将所有输出数据存储在内存中,并使用
    File.writeAllines
    一次性写入所有数据

  • 如果无法将所有内容都存储在内存中,则可以将所有内容写入临时文件,然后将该文件复制到目标


  • 您使用的是哪种反病毒?@mjwills Avira@ZevSpitz不调用
    File.AppendAllLines
    。如果知道要多次访问同一文件,请创建一个
    StreamWriter
    ,并在方法中使用它。现在,每次打开/关闭流只是为了写几行代码,你就要为此付出代价。其他进程也在做同样的事情吗?或者你只有一个进程来处理这个文件?如果你的程序只有一个线程和一个实例,那么我猜应该是杀毒软件,暂时禁用它,你就会看到它是否有效果。如果exe没有数字签名,Anitvirus软件会更加关注。因此,如果您的代码将在生产环境中使用,您应该考虑代码签名。另一种解决方案是重试循环,该循环尝试n次结束行,假设失败的
    AppendLines
    中没有任何行已经写入。