假設VS代碼對應路徑為E:\Projects\Web1,在VS用“發布Web”的方式發布后的路徑為E:\Site\Web1。
在IIS新建2個站點,站點A指向E:\Projects\Web1,站點B指向E:\Site\Web1。
現在出現一個異常情況,站點B能正常下載123.xls,站點A下載時卻提示錯誤:
System.UnauthorizedAccessException: 對路徑“E:\Projects\Web1\Download\123.xls”的訪問被拒絕。
在 System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
在 System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
在 System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
在 System.IO.FileStream..ctor(String path, FileMode mode)
站點A和站點B的目錄和文件權限一模一樣,特意為站點A增加了權限等還是無效,搜索了一下,最后找到了解決方法,把下載代碼里面的
FileStream fs = File.Open(filePath, FileMode.Open)
改為就可以下載了。
FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read);
官方MSDN文檔如下:
File.Open 方法 (String, FileMode)
打開指定路徑上的 FileStream,具有讀/寫訪問權限。
異常 UnauthorizedAccessException
path 指定了一個只讀文件。
- 或 -
在當前平台上不支持此操作。
- 或 -
path 指定了一個目錄。
- 或 -
調用方沒有所要求的權限。
- 或 -
mode 為 Create,指定文件為隱藏文件。
這時候回過頭再去看E:\Projects\Web1\Download\123.xls,果然是只讀屬性,
而E:\Site\Web1\Download\123.xls沒有只讀屬性;
把E:\Projects\Web1\Download\123.xls的只讀屬性去掉,重新恢復剛開始的代碼
FileStream fs = File.Open(filePath, FileMode.Open); 這時下載就正常。
總結,解決方法有2種:
1、把文件的只讀屬性去掉;
2、FileStream fs = File.Open(filePath, FileMode.Open)改用下面這行代碼
FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read);