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

时间:2019-05-27 09:35:14

标签: c# .net-core

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

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)");

    ...
}

和一个定义RunTest的实现的类:

class ConstructedTestData : ConstructedBase {
    protected override void RunTest(object o, string csharp, string vb, string factoryMethods) => Runner.WriteData(o, factoryMethods);
}

转发到static方法:

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中同时打开文本文件时,才会出现此错误。

2 个答案:

答案 0 :(得分:0)

该问题很可能是Visual Studio(或防病毒)对该文件持有了锁定。

您应该在Visual Studio中将其关闭。

答案 1 :(得分:0)

两种选择:

  1. 将所有输出数据存储在内存中,并使用File.WriteAllLines一次写入所有数据。

  2. 如果将所有内容存储在内存中是不切实际的,则有可能将所有内容写入一个临时文件,然后将该文件复制到目标位置。