2017-04-18 541 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; 
    }