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);
        }

複製代碼

總結

在操作文件的時候,還是比較簡單的,不過文件夾就比較複雜了,涉及是否要繼承的問題。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章