C# 設定U盤的屬性-安全-許可權為讀取和執行
阿新 • • 發佈:2019-02-06
/// <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 ,也是需要兩個使用者組都修改哦,程式碼就不貼出來啦