Asp.net System.IO.File.ReadAllBytes对路径的访问被拒绝
我在visual studio 2015上运行该项目,当我试图阅读PDF时,它给了我以下错误 对路径“E:\FILE\FILEUPLOAD\InnerFile\FILE”的访问被拒绝 功能定义Asp.net System.IO.File.ReadAllBytes对路径的访问被拒绝,asp.net,pdf,readfile,Asp.net,Pdf,Readfile,我在visual studio 2015上运行该项目,当我试图阅读PDF时,它给了我以下错误 对路径“E:\FILE\FILEUPLOAD\InnerFile\FILE”的访问被拒绝 功能定义 var cd = new System.Net.Mime.ContentDisposition { FileName = "PDF.pdf", Inline = true }; string contentType = MimeMapping.GetMimeMapp
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);
注意:
- 已授予用户完全权限
- 物理文件存在
尝试使用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。组合将路径部分粘合在一起,而不是简单的字符串连接…在处理新文件信息(PDFUploadRootPath+innerPath+“/PDF.PDF”)这样的路径时,不要使用字符串连接代码>,使用路径。合并
。我看到您使用的是正斜杠/
而不是反斜杠-假设您在Windows上运行,它是不正确的路径分隔符。是的,我在Windows上运行它。。。检查“fi.Exists”时找到文件。因此,在读取@marcinzablockii时给出错误的路径没有问题。如果您的目的是从路径PDFUploadRootPath+innerPath+“/PDF.PDF”
,那么您就不会在下一行中执行此操作:System.IO.file.ReadAllBytes(PDFUploadRootPath+innerPath)
.Plus-可能您的权限中有拒绝访问权限(拒绝访问规则将覆盖NTFS中的允许权限规则)。您能告诉我该如何修复此错误吗?啊,Thanx mate这是一个最愚蠢的错误:(