0

这段代码:

string ticklerFile = "awardUpdateDates.txt";
StringBuilder replacementFile = new StringBuilder();
List<string> lions = File.ReadAllLines(ticklerFile).ToList();
foreach (string lion in lions)
{
    if (lion.Contains("Pulitzer"))
    {
        string newLine = string.Format("Pulitzer~{0}", DateTime.Now.ToString("d"));
        replacementFile.Append(newLine + Environment.NewLine); 
        continue;
    }
    replacementFile.Append(lion + Environment.NewLine);
}
File.WriteAllText(ticklerFile, replacementFile.ToString());

...在最后一行失败,

"*System.IO.IOException was unhandled
  HResult=-2147024864
  Message=The process cannot access the file 'C:\AwardWinnersOnlyOriginal12UpdateUtil\AWO12OriginalUpdateUtil\bin\Debug\awardUpdateDates.txt' because it is being used by another process.*"

该文件未在其他地方打开,我可以看到。它在File.ReadAllLines()被调用时被打开,但是没有File.Close()可用的,所以我不知道这是否是一个问题,如果是,如何解决它。

更新

我想也许我可以用这段代码解决我的问题:

string ticklerFile = "awardUpdateDates.txt";
string newLine;
StringBuilder replacementFile = new StringBuilder();
List<string> lions = File.ReadAllLines(ticklerFile).ToList();
File.Delete(ticklerFile);
foreach (string lion in lions)
{
    if (lion.Contains("Pulitzer"))
    {
        newLine = string.Format("Pulitzer~{0}", DateTime.Now.ToString("d"));

    }
    else
    {
        newLine = lion;
    }
    replacementFile.Append(newLine);
}
File.WriteAllText(ticklerFile, replacementFile.ToString());

...但是我在 File.Delete() 行上遇到了同样的错误。

4

0 回答 0