我想列出用户具有读取权限的文件夹中的所有文件。用户访问该网站并可以对网站的某些方面使用表单身份验证(例如添加链接等),但我想使用他们的 Windows 凭据列出给定文件夹中的文件(因为我关闭了匿名访问),隐藏那些他们无法阅读。
但是,在使用时Directory.GetFiles
,它还包括无法读取的文件(尽管可以读取元数据(文件大小、创建日期等))。
这就是我所拥有的:
string[] files;
string[] folders;
string rootDir = @"\\server\path\to\dir\";
WindowsIdentity id = (WindowsIdentity)User.Identity ;
using (System.Security.Principal.WindowsImpersonationContext context = System.Security.Principal.WindowsIdentity.Impersonate(id.Token))
{
files = Directory.GetFiles(rootDir);
folders = Directory.GetDirectories(rootDir);
foreach (string file in files)
{
FileInfo fi = new FileInfo(file);
FileSecurity fs = fi.GetAccessControl(AccessControlSections.Access);
//foreach (FileSystemAccessRule rule in fs.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier)))
//{
// Response.Write((FileSystemRights.Read & rule.FileSystemRights) + " <br />");
//}
Response.Write(file + " " + fi.Length + "<br />");
}
context.Undo();
}
当我访问该页面时,我UnauthorizedAccessException
一使用就会得到GetAccessControl
,即使它应该使用当前的用户凭据。using
由于 asp.net 帐户无权访问该文件夹,因此关闭失败。当FileSecurity
被注释掉时,它会列出所有文件。
堆栈跟踪:
[UnauthorizedAccessException: Attempted to perform an unauthorized operation.]
System.Security.AccessControl.Win32.GetSecurityInfo(ResourceType resourceType, String name, SafeHandle handle, AccessControlSections accessControlSections, RawSecurityDescriptor& resultSd) +697
System.Security.AccessControl.NativeObjectSecurity.CreateInternal(ResourceType resourceType, Boolean isContainer, String name, SafeHandle handle, AccessControlSections includeSections, Boolean createByName, ExceptionFromErrorCode exceptionFromErrorCode, Object exceptionContext) +63
System.Security.AccessControl.FileSystemSecurity..ctor(Boolean isContainer, String name, AccessControlSections includeSections, Boolean isDirectory) +86
System.Security.AccessControl.FileSecurity..ctor(String fileName, AccessControlSections includeSections) +42
System.IO.FileInfo.GetAccessControl(AccessControlSections includeSections) +29
UNCDirectory.Page_Load(Object sender, EventArgs e) +213
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +50
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627
关于如何做到这一点的任何想法,而无需尝试打开每个文件并捕获发生的异常?