C#编程实现访问系统文件夹的代码

    技术2024-04-15  14

    在Windows系统中有很多文件夹是受系统保护的,比如System Volume Information,中文名称可以翻译为“系统卷标信息”,这个文件夹里就存储着系统还原的备份信息。对于这类系统资源,C#应用程序是无法直接访问 其中的子目录和文件的,所以必须让Windows认为我们程序的当前访问是安全的,才能让我们访问,这就要用到 System.Security.AccessControl命名空间了,它提供了有关安全访问系统资源的方法。

    下面是C# 写的一个获取受保护文件夹的子目录的函数:

    //注意添加名称空间的引用:using System.Security.AccessControl;

    private DirectoryInfo[] GetDirList(DirectoryInfo dirInfo) {     if (dirInfo == null || !dirInfo.Exists)         return null;     DirectoryInfo[] dirInfos = null;     try     {         //一般情况下,按正常方法获取目录列表         dirInfos = dirInfo.GetDirectories();     }     catch { }     //如果不为空,那么说明目录列表成功,否则需要添加安全访问规则     if (dirInfos != null)         return dirInfos;

        //新建账户安全访问规则     FileSystemAccessRule fsRule = new FileSystemAccessRule(System.Environment.UserName         , FileSystemRights.Modify, AccessControlType.Allow);

        //添加安全访问规则     DirectorySecurity dirSecurity = dirInfo.GetAccessControl();     dirSecurity.AddAccessRule(fsRule);     dirInfo.SetAccessControl(dirSecurity);

        try     {         dirInfos = dirInfo.GetDirectories();     }     catch (Exception ex)     {         MessageBox.Show("无法访问文件夹:" + dirInfo.FullName + "/n" + ex.Message);     }     //移除安全访问规则     dirSecurity = dirInfo.GetAccessControl();     dirSecurity.RemoveAccessRule(fsRule);     dirInfo.SetAccessControl(dirSecurity);     return dirInfos; }

    最新回复(0)