C# File.WriteAllText进程无法访问该文件,因为其他进程正在使用该文件

C# File.WriteAllText进程无法访问该文件,因为其他进程正在使用该文件,c#,exception,text-files,console-application,C#,Exception,Text Files,Console Application,我正在使用此代码写入文本文件: int num; StreamWriter writer2; bool flag = true; string str = ""; if (flag == File.Exists(this.location)) { File.WriteAllText(this.location, string.Empty); new FileInfo(this.location).Open(FileMode.Truncate).Close(); using

我正在使用此代码写入文本文件:

int num;
StreamWriter writer2;
bool flag = true;
string str = "";
if (flag == File.Exists(this.location))
{
    File.WriteAllText(this.location, string.Empty);
    new FileInfo(this.location).Open(FileMode.Truncate).Close();
    using (writer2 = this.SW = File.AppendText(this.location))
    {
        this.SW.WriteLine("Count=" + this.Count);
        for (num = 0; num < this.Count; num++)
        {
            this.SW.WriteLine(this.Items[num]);
        }
        this.SW.Close();
    }
}

但是,我检查了文本文件,发现它已被更新。

如果
字符串
的可枚举项,则应该能够用以下内容替换所有代码

if (File.Exists(this.location))
    File.WriteAllLines(this.location, this.Items);   
如果不是,并且您正在利用
Items
中每个对象的
ToString()
,则可以执行以下操作:

if (File.Exists(this.location))
{
    var textLines = Items.Select(x => x.ToString());
    File.WriteAllLines(this.location, textLines);   
}
这将解决文件被锁定的问题,因为它只访问一次文件,而原始代码将其打开3次

编辑:刚刚注意到您添加了一个“计数”行。这里有一个使用流的更干净的版本

if (File.Exists(this.location))
{
    using (var fileInfo = new FileInfo(this.location)
    {
        using(var writer = fileInfo.CreateText())
        {
            writer.WriteLine("Count=" + Items.Count);
            foreach(var item in Items)
                writer.WriteLine(item);
        }
    }
}

您可以去掉
this.SW.Close()-
使用
可以帮你做到这一点。无意冒犯,但是你的代码看起来真的很吓人。您应该能够通过使用
File.writeAllines
,替换所有的编写代码和多个流——试试这个-if(flag==File.Exists(this.location){File.Delete(this.location);}
if (File.Exists(this.location))
{
    using (var fileInfo = new FileInfo(this.location)
    {
        using(var writer = fileInfo.CreateText())
        {
            writer.WriteLine("Count=" + Items.Count);
            foreach(var item in Items)
                writer.WriteLine(item);
        }
    }
}