1

我正在使用 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);
}

但是它抛出了异常:The process cannot access the file 'path\to\file.html' because it is being used by another process.
我担心这种情况正在发生,因为File.ReadAllTextorFile.WriteAllText方法正在文件上运行,即使在文档中它指定它们确实关闭了文件。那么有人知道是什么原因造成的吗?

4

2 回答 2

7

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

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

于 2013-06-11T20:01:30.293 回答
0

每当您处理Stream基于对象时,最好使用using语句包装:

String s1;
using (StreamReader r = new StreamReader(paramExportFilePath, Encoding.ASCII))
{
    s1 = r.ReadToEnd();
}
String s2 = s1.Replace("string to delete", "replacement string");
using (StreamWriter w = new StreamWriter(paramExportFilePath, false, Encoding.ASCII))
{
    w.Write(s2);
}

这些using语句确保对象被正确关闭,更重要的是,被处置。

注意:将 Encoding.ASCII 替换为您喜欢的任何内容(如果是 HTML 代码,则可能是 UTF8)。

于 2013-06-11T20:15:54.027 回答