C# 设置U盘的属性-安全-权限为读取和执行

/// <summary>
/// U盘读取和执行
/// </summary>
private void UDiskReadAndExecute()
{
    //获得所有的驱动器
    DriveInfo[] s = DriveInfo.GetDrives();
    foreach (DriveInfo drive in s)
    {
        //表示移动盘
        if (drive.DriveType == DriveType.Removable)
        {
            DirectorySecurity dirSecurity = drive.RootDirectory.GetAccessControl(AccessControlSections.All);
            InheritanceFlags inherits = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
            FileSystemAccessRule everyoneFileSystemAccessRule = new FileSystemAccessRule("Everyone", FileSystemRights.ReadAndExecute, inherits, PropagationFlags.None, AccessControlType.Allow); 
            FileSystemAccessRule usersFileSystemAccessRule = new FileSystemAccessRule("Users", FileSystemRights.ReadAndExecute, inherits, PropagationFlags.None, AccessControlType.Allow);
            bool isModified = false;
            dirSecurity.ModifyAccessRule(AccessControlModification.Set, usersFileSystemAccessRule, out isModified);
            dirSecurity.ModifyAccessRule(AccessControlModification.Set, everyoneFileSystemAccessRule, out isModified);
            drive.RootDirectory.SetAccessControl(dirSecurity);
        }
    }
}

上面就是设置U盘的属性-安全-权限为读取和执行的代码了,如果设置所有权限

将上面代码的 FileSystemRights.ReadAndExecute 改为 FileSystemRights.FullControl ,别忘记两个用户组都需要修改哦,如果你只需要一个用户组也可以将 Users 或者 Everyone 相应的代码删除。

代码:

/// <summary>
/// U盘完全控制
/// </summary>
private void UDiskFullControl()
{
    //获得所有的驱动器
    DriveInfo[] s = DriveInfo.GetDrives();
    foreach (DriveInfo drive in s)
    {
        //表示移动盘
        if (drive.DriveType == DriveType.Removable)
        {
            DirectorySecurity dirSecurity = drive.RootDirectory.GetAccessControl(AccessControlSections.All);
            InheritanceFlags inherits = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
            FileSystemAccessRule everyoneFileSystemAccessRule = new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow); 
            FileSystemAccessRule usersFileSystemAccessRule = new FileSystemAccessRule("Users", FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);
            bool isModified = false;
            dirSecurity.ModifyAccessRule(AccessControlModification.Set, usersFileSystemAccessRule, out isModified);
            dirSecurity.ModifyAccessRule(AccessControlModification.Set, everyoneFileSystemAccessRule, out isModified);
            drive.RootDirectory.SetAccessControl(dirSecurity);
        }
    }
}

如果设置拒绝所有访问,则是将上面完全控制的代码中 AccessControlType.Allow 改为 AccessControlType.Deny ,也是需要两个用户组都修改哦,代码就不贴出来啦

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值