使用C#File类编辑文件,但抛出异常

azr*_*n92 1 .net c#

我正在使用File类来编辑HTML文件.我需要从中删除一行代码.我这样做的方式是:

if (selectedFileType.Equals("html"))
{
    string contentsOfHtml = File.ReadAllText(paramExportFilePath);
    //delete part that I don't want
    string deletedElement = "string I need to delete";
    contentsOfHtml.Replace(deletedElement, "");
    File.WriteAllText(paramExportFilePath, contentsOfHtml);
}
Run Code Online (Sandbox Code Playgroud)

然而它抛出了异常:The process cannot access the file 'path\to\file.html' because it is being used by another process.
我担心这种情况正在发生,因为File.ReadAllText或者File.WriteAllText方法正在文件上运行,即使在文档中它指定它们关闭文件.那么有谁知道这可能导致什么?

squ*_*man 7

如果这是一个实时站点上的文件,那么Web服务器很可能锁定它.

假设您在Windows中工作,请尝试使用Process Explorer查看文件锁定的内容.