【问题标题】:File is being used by another process while using WriteAllText in c#在 c# 中使用 WriteAllText 时,另一个进程正在使用文件
【发布时间】:2016-04-13 04:31:21
【问题描述】:

如果指定位置存在,我正在检查文件是否存在,如果存在,我将用 ' 替换单引号。为此,我使用的是 WriteAllText 方法。据我所知,WriteAllText 将用于Create file and write the text and close it, target file is already exists, it will be overwritten

我不知道为什么我在使用时收到System.IOException

var file = AppDomain.CurrentDomain.BaseDirectory + "test";
if (Directory.Exists(file))
{
    string text = File.ReadAllText(file + "\\test.txt");
    text = text.Replace("'", "&#39");
    File.WriteAllText(file + "\\test.txt", text);
}

注意:我在 Application_BeginRequest 方法中使用这个。

建议我如何避免这个异常?

【问题讨论】:

  • 只需交叉验证使用它的任何其他应用程序(如记事本等)..
  • 当您收到IOException 时,它说的是InnerException?这应该让您知道出了什么问题。

标签: c# file writealltext


【解决方案1】:

使用您的代码,如下所示

            var file = AppDomain.CurrentDomain.BaseDirectory + "test.txt";
            if (File.Exists(file))
            {
                string text = File.ReadAllText(file);
                text = text.Replace("'", "&#39");
                File.WriteAllText(file, text);
            }

希望这能解决您的问题

【讨论】:

    【解决方案2】:

    首先, 您在使用时询问目录是否存在

    Directory.Exists(file)
    

    为了检查你需要使用的文件是否存在

    File.Exists(file)
    

    其次, 您试图通过再次将与文件名连接的文件作为参数传递来从文件中读取所有文本。所以你传递的文件名实际上是:

    AppDomain.CurrentDomain.BaseDirectory + "test.txt" + "\\test.txt";
    

    第三,WriteAllText 的注释与 ReadAllText 的注释相同。

    网上有很多例子可以学习如何从文件中读写,例如:

    Read from a Text File - MSDN
    Write to a Text File - MSDN

    【讨论】:

    • 你应该给你的变量起有意义的名字。不要将文件调用到表示目录的变量。例如,如果 directoryPath 或 folderPath 调用。修复后,您还有问题吗?
    • 我添加了一个条件来检查文件是否有单引号。如果(文本。包含(“'”))。现在我没有得到例外。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-01
    • 2013-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多