System.IO.File.ReadAllBytes 访问路径被拒绝

System.IO.File.ReadAllBytes Access to the path denied

我是 运行 visual studio 2015 年的项目,当我尝试阅读 PDF 时出现以下错误;

Access to the path 'E:\FILE\FILEUPLOAD\InnerFile\File' is denied.

函数定义

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

注意:

  • Given Full permission to user
  • Physically File Exists

我现在不知道该怎么办,请帮忙!

尝试使用 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;
    }

您的 FileInfo 实例确实引用了 'E:\FILE\FILEUPLOAD\InnerFile\File\PDF.pdf':

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

但是在尝试读取文件内容时忘记了文件名,只使用路径 'E:\FILE\FILEUPLOAD\InnerFile\File':

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

因此,还要加上读取所有文件字节的文件名:

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

此外,正如其他人在评论中提到的,您应该真正使用 Path.Combine 将路径部分粘合在一起,而不是简单的字符串连接...