-2

如果指定位置,我正在检查文件是否存在,如果是,我将用 ' 替换单引号。为此,我使用的是 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方法。

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

4

2 回答 2

0

使用您的代码,如下所示

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

希望这能解决你的问题

于 2016-04-13T04:50:22.783 回答
0

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

Directory.Exists(file)

为了检查文件的存在,您需要使用

File.Exists(file)

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

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

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

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

从文本文件读取 - MSDN
写入文本文件 - MSDN

于 2016-04-13T04:57:39.240 回答