簡體   English   中英

使用File.Open拒絕訪問路徑(路徑名)

[英]Access to the path (path name) is denied using 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事件消息:發生未處理的訪問異常。

可能是因為您要使用FilePath而不是您計算出的PathToFile調用FileOpen ,所以:

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");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM