C#修改文件或文件夹的权限,为指定用户、用户组添加完全控制权限
生活随笔
收集整理的這篇文章主要介紹了
C#修改文件或文件夹的权限,为指定用户、用户组添加完全控制权限
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
寫在前面
在windows系統中,c盤中的目錄權限比較高,有時制作安裝包的時候,默認的安裝路徑就是在c盤,但對運行可執行文件,有時候需要為其添加完全控制權限,或者讀寫權限。這里將當時的解決方案記錄一下。
代碼實現
在C盤添加一個文件夾,并在文件夾內部,新建一個文本文件,如圖所示:
該文件夾下,新建一個文本文件,如圖所示:
為文件添加完全控制權限:
/// <summary>/// 為文件添加users,everyone用戶組的完全控制權限/// </summary>/// <param name="filePath"></param>static void AddSecurityControll2File(string filePath){//獲取文件信息FileInfo fileInfo = new FileInfo(filePath);//獲得該文件的訪問權限System.Security.AccessControl.FileSecurity fileSecurity = fileInfo.GetAccessControl();//添加ereryone用戶組的訪問權限規則 完全控制權限fileSecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));//添加Users用戶組的訪問權限規則 完全控制權限fileSecurity.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow));//設置訪問權限fileInfo.SetAccessControl(fileSecurity);}為文件夾添加完全控制權限
/// <summary>///為文件夾添加users,everyone用戶組的完全控制權限/// </summary>/// <param name="dirPath"></param>static void AddSecurityControll2Folder(string dirPath){//獲取文件夾信息DirectoryInfo dir = new DirectoryInfo(dirPath);//獲得該文件夾的所有訪問權限System.Security.AccessControl.DirectorySecurity dirSecurity = dir.GetAccessControl(AccessControlSections.All);//設定文件ACL繼承InheritanceFlags inherits = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;//添加ereryone用戶組的訪問權限規則 完全控制權限FileSystemAccessRule everyoneFileSystemAccessRule = new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);//添加Users用戶組的訪問權限規則 完全控制權限FileSystemAccessRule usersFileSystemAccessRule = new FileSystemAccessRule("Users", FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);bool isModified = false;dirSecurity.ModifyAccessRule(AccessControlModification.Add, everyoneFileSystemAccessRule, out isModified);dirSecurity.ModifyAccessRule(AccessControlModification.Add, usersFileSystemAccessRule, out isModified);//設置訪問權限dir.SetAccessControl(dirSecurity);}總結
在操作文件的時候,還是比較簡單的,不過文件夾就比較復雜了,牽扯到是否要繼承的問題。
總結
以上是生活随笔為你收集整理的C#修改文件或文件夹的权限,为指定用户、用户组添加完全控制权限的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 米兰理工大学(说一说米兰理工大学的简介)
- 下一篇: 一代枭雄之三支旗迅雷下载 1080P(一