c# - 使用 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 事件消息:发生未处理的访问异常。
解决方案
也许是因为你打电话FileOpen
而FilePath
不是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");
}
推荐阅读
- javascript - electron.ipcMain 的奇怪行为
- flutter - 如何让视频在不拉伸的情况下填满屏幕(使用 Chewie 或类似工具)?
- reactjs - 变量在反应事件总线上没有得到正确的值
- python - 使用 Python 通过 Linux 服务器将 pandas 写入 SQL Server
- google-cloud-platform - 如何将 pyspark ml 代码运行到 gcp 集群中?
- vue.js - API 需要设置用户代理,但它在 chrome 中是不安全的标头
- swift - 如何确保正确处理 VisionImage(来自 Google 在 Firebase 中的 ML Kit)对象?
- javascript - 切换状态组件的未定义 e.target.name
- grep - 如何确定由于特定大小而更高的重叠群数量
- python - Python 代码在 watson-studio 中不起作用?