read/write 从 asp.net 应用程序对文本文件的操作

read/write operation to text file from asp.net application

我正在尝试 read/write 到位于我网站根目录的文本文件。我正在使用 asp.net 开发服务器(我的本地机器)。

当我读取文件时它抛出这个异常

Access to the path 'C:\Program Files\Common Files\Microsoft Shared\DevServer.0\error.txt' is denied.

我正在使用以下代码行 read/write 来自文本文件

 var text = File.ReadAllText(Server.MapPath("error.txt"));
    File.WriteAllText(@"error.txt", text + " \n " + "newnewnew text");

有什么问题,为什么我的 server.MapPath 检索我的 C 盘路径?当它应该检索我网站的绝对路径时,即

website1/error.txt

如果您更改以下行

File.ReadAllText(Server.MapPath("error.txt"));

File.ReadAllText(Server.MapPath("~/error.txt"));

它将在应用程序的根目录中搜索文件。如果您将文件存储在根目录中名为 "MyFiles" 的文件夹中,那么路径将类似于下面的内容

File.ReadAllText(Server.MapPath("~/MyFiles/error.txt"));

希望对您有所帮助。