2017-04-18 157 views
0

在Visual Studio 2015上運行項目時,當我嘗試閱讀PDF時,它給了我以下錯誤;System.IO.File.ReadAllBytes訪問被拒絕的路徑

訪問路徑'E:\ FILE \ FILEUPLOAD \ InnerFile \ File'被拒絕。

功能界定及

var cd = new System.Net.Mime.ContentDisposition { FileName = "PDF.pdf", Inline = true }; 

       string contentType = MimeMapping.GetMimeMapping("PDF.pdf"); 
    Response.AppendHeader("Content-Disposition", cd.ToString()); 
    var innerPath = "InnerFile/File" ; 

       FileInfo fi = new FileInfo(PDFUploadRootPath + innerPath + "/PDF.pdf"); 

byte[] bytes = System.IO.File.ReadAllBytes(PDFUploadRootPath + innerPath); 

      return File(bytes, contentType); 

注:

  • 給予充分的權限用戶
  • 物理文件存在

我不明白該怎麼做,請幫忙!

enter image description here

+0

不要在處理像這樣的路徑時使用字符串連接,新的FileInfo(PDFUploadRootPath + innerPath +「/PDF.pdf」);使用Path.Combine'''。我看到你有正斜槓'''''''不反斜槓 - 假設你在Windows上運行,它是不合適的路徑分隔符。 –

+0

是m在Windows上運行它...檢查'fi.Exists'時找到文件。所以它的路徑沒有問題,在閱讀@MarcinZablocki時給出錯誤 –

+1

如果你的意圖是從路徑「PDFUploadRootPath + innerPath +」/PDF.pdf「'''讀取文件,那麼你不這樣做在下一行:'''System.IO.File.ReadAllBytes(PDFUploadRootPath + innerPath)'''。 –

回答

1

FileInfo實例確實引用了「E:\ FILE \文件上傳\ InnerFile \文件\ PDF.pdf 「:

FileInfo fi = new FileInfo(PDFUploadRootPath + innerPath + "/PDF.pdf"); 

,但在嘗試讀取您忘記文件名的文件內容,僅使用路徑時, 'E:\ FILE \ \文件文件上傳\ InnerFile':

byte[] bytes = System.IO.File.ReadAllBytes(PDFUploadRootPath + innerPath); 

因此,也可用於讀取所有文件的字節添加文件名:

byte[] bytes = System.IO.File.ReadAllBytes(PDFUploadRootPath + innerPath + "/PDF.pdf"); 

此外,如別人的意見所提到的,你應該使用Path.Combine膠水路徑部分組合在一起,而不是簡單的字符串連接...

+0

AHHHHHHH,Thanx隊友,這是一個愚蠢的錯誤:( –

0

嘗試使用的FileStream代替字節數組,用於讀取該PDF文件。

FileStream templateFileStream = File.OpenRead(filePath); 
      return templateFileStream; 

還要檢查(通過代碼),如果用戶有寫權限的目錄或路徑:

public static bool HasUserWritePermission(String path, String NtAccountName) 
    { 
     DirectoryInfo di = new DirectoryInfo(path); 
     DirectorySecurity acl = di.GetAccessControl(AccessControlSections.All); 
     AuthorizationRuleCollection rules = acl.GetAccessRules(true, true, typeof(NTAccount)); 
     Boolean hasPermission = false; 
     //Go through the rules returned from the DirectorySecurity 
     foreach (AuthorizationRule rule in rules) 
     { 
      //If we find one that matches the identity we are looking for 
      if (rule.IdentityReference.Value.Equals(NtAccountName, StringComparison.CurrentCultureIgnoreCase)) 
      { 
       //Cast to a FileSystemAccessRule to check for access rights 
       if ((((FileSystemAccessRule)rule).FileSystemRights & FileSystemRights.WriteData) > 0) 
       { 
        hasPermission = true; 
       } 
       else 
       { 
        hasPermission = false; 
       } 
      } 
     } 
     return hasPermission; 
    }