我正在尝试编写一个功能,我可以在所有驱动器中获取所有文件名的完整列表,但我被困在一个地方,它给我安全异常来读取所有文件。 我浏览了本网站和其他文章中的许多文章,但无法弄清楚如何设置完整的访问权限
这篇文章非常有用,但我得到了一个在该帖子中没有回复的例外
How to grant read access to all files in a folder and subfolders using c#?
现在我的代码看起来像这样
[FileIOPermission(SecurityAction.LinkDemand, Read = "C:\\")]
public void GetAllFilesFromPhysicalDrives()
{
List<DriveInfo> allphydrives = GetListofPhysicalDrivesOnly(); //Gets All Physical DrivesCollection
try
{
foreach (DriveInfo dr in allphydrives)
{
DirectoryInfo dir = new DirectoryInfo(dr.Name);
DirectorySecurity dirSecurity = dir.GetAccessControl();
dirSecurity.AddAccessRule(new FileSystemAccessRule(Environment.UserName, FileSystemRights.Read, AccessControlType.Allow));
dir.SetAccessControl(dirSecurity);
FileSystemAccessRule faRule;
FileSystemRights fsrRights;
DirectorySecurity dirsec;
fsrRights = FileSystemRights.FullControl;
faRule = new FileSystemAccessRule(new System.Security.Principal.NTAccount("my-pc\\me"),fsrRights,InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit,PropagationFlags.InheritOnly, AccessControlType.Allow);
System.Security.Principal.NTAccount account = new System.Security.Principal.NTAccount("me\\me");
dirsec = Directory.GetAccessControl("C:\\");
dirsec.SetOwner(account);
dirsec.AddAccessRule(faRule);
Directory.SetAccessControl("C:\\", dirsec);
}
}
catch(Exception ex)
{
}
}
所以当设置访问权限的代码执行时,我得到“尝试执行未授权操作”异常
我不想逐个设置文件的权限,因为它是一项繁琐的任务,所以帮助我通过所有文件夹的代码动态发生,这样我就可以迭代并获取所有文件名。(我不打算获取与Windows相关的文件或内核文件,只需用户创建的文件即可)