1. 程式人生 > >C#修改文件或文件夾的權限,為指定用戶、用戶組添加完全控制權限

C#修改文件或文件夾的權限,為指定用戶、用戶組添加完全控制權限

pat rule bubuko allow use 寫在前面 操作 ces container

寫在前面

在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#修改文件或文件夾的權限,為指定用戶、用戶組添加完全控制權限