从应用程序读/写到文本文件的操作 asp.net

本文关键字:文件 操作 asp net 文本 应用程序 | 更新日期: 2023-09-27 18:37:09

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

当我读取文件时,它抛出此异常

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

我使用以下代码行从文本文件读取/写入

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

问题是什么,为什么是我的服务器。地图路径检索我的c驱动器的路径?当它应该检索我的网站的绝对路径时,即

website1/error.txt

从应用程序读/写到文本文件的操作 asp.net

如果更改以下行

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

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

它将在应用程序的根目录中搜索文件。如果您将文件存储在根目录中名为"MyFiles"的文件夹中,则路径将如下所示

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

希望这有帮助。