C#修改文件或文件夾的權限,爲指定用戶、用戶組添加徹底控制權限

寫在前面

在windows系統中,c盤中的目錄權限比較高,有時製做安裝包的時候,默認的安裝路徑就是在c盤,但對運行可執行文件,有時候須要爲其添加徹底控制權限,或者讀寫權限。這裏將當時的解決方案記錄一下。windows

代碼實現

在C盤添加一個文件夾,並在文件夾內部,新建一個文本文件,如圖所示:spa

該文件夾下,新建一個文本文件,如圖所示:3d

爲文件添加徹底控制權限:code

複製代碼
        /// <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);
        }
複製代碼

爲文件夾添加徹底控制權限blog

複製代碼
        /// <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);
        }
複製代碼

總結

在操做文件的時候,仍是比較簡單的,不過文件夾就比較複雜了,牽扯到是否要繼承的問題。繼承

相關文章
相關標籤/搜索