首页 > 解决方案 > 使用 File.Open 拒绝访问路径(路径名)

问题描述

在 Windows 10 机器上本地调试,VS2015。

我需要打开一个只有读取权限的文件。该文件存在于 Web 应用程序的子文件夹中。

这会引发异常:

System.UnauthorizedAccessException:对路径“F:\webroot\subfolder”的访问被拒绝。

我尝试添加具有完全权限的每个人,添加具有完全权限的每个用户,打开安全策略审核并检查安全日志以发现请求用户,但那里没有出现任何内容,好像它实际上不是安全错误,不同的文件夹名称,以及我可以在网上找到的所有其他内容,包括添加 ASPNET 用户 - 没有要添加的此类用户。

计算出的路径是正确的物理磁盘路径。该路径位于 webroot 内部。

string FilePath = HttpContext.Current.Server.MapPath("\\Upload");
string PathToFile = FilePath + "\\" + idFileName;
Stream fs = File.Open(FilePath, FileMode.Open, FileAccess.Read);

最后一行代码抛出异常。

ASP.NET 网页输出:拒绝访问路径“F:\webrootname\Upload”。

应用程序事件日志:

事件代码:4011 事件消息:发生未处理的访问异常。

标签: c#asp.net

解决方案


也许是因为你打电话FileOpenFilePath不是PathToFile你计算的,所以:

Stream fs = File.Open(PathToFile, FileMode.Open, FileAccess.Read);

此外,您可以在打开文件之前进一步测试文件是否存在:

string FilePath = HttpContext.Current.Server.MapPath("\\Upload");
string PathToFile = FilePath + "\\" + idFileName;
if(System.IO.File.Exists(PathToFile))
{
    Stream fs = File.Open(PathToFile, FileMode.Open, FileAccess.Read);
}
else
{
    // use whatever logger to trace your application
    log.Error("The file : + PathToFile + " does not exist");
}

推荐阅读