C#設(shè)置文件權(quán)限的方法
在開發(fā)中,我們經(jīng)常會(huì)使用IO操作,例如創(chuàng)建,刪除文件等操作。在項(xiàng)目中這樣的需求也較多,我們也會(huì)經(jīng)常對(duì)這些操作進(jìn)行編碼,但是對(duì)文件的權(quán)限進(jìn)行設(shè)置,這樣的操作可能會(huì)手動(dòng)操作,現(xiàn)在介紹一種采用代碼動(dòng)態(tài)對(duì)文件設(shè)置權(quán)限的操作。
在對(duì)文件進(jìn)行權(quán)限設(shè)置在DOtNet中,會(huì)采用FileSystemAccessRule類進(jìn)行文件的權(quán)限操作。
1.現(xiàn)在看一下FileSystemAccessRule的實(shí)現(xiàn)代碼:
public FileSystemAccessRule( IdentityReference identity, FileSystemRights fileSystemRights, AccessControlType type ) : this( identity, AccessMaskFromRights( fileSystemRights, type ), false, InheritanceFlags.None, PropagationFlags.None, type ) { } public FileSystemAccessRule( String identity, FileSystemRights fileSystemRights, AccessControlType type ) : this( new NTAccount(identity), AccessMaskFromRights( fileSystemRights, type ), false, InheritanceFlags.None, PropagationFlags.None, type ) { } // // Constructor for creating access rules for folder objects // public FileSystemAccessRule( IdentityReference identity, FileSystemRights fileSystemRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type ) : this( identity, AccessMaskFromRights( fileSystemRights, type ), false, inheritanceFlags, propagationFlags, type ) { } public FileSystemAccessRule( String identity, FileSystemRights fileSystemRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type ) : this( new NTAccount(identity), AccessMaskFromRights( fileSystemRights, type ), false, inheritanceFlags, propagationFlags, type ) { } internal FileSystemAccessRule( IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type ) : base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags, type ) { } #endregion #region Public properties public FileSystemRights FileSystemRights { get { return RightsFromAccessMask( base.AccessMask ); } } internal static int AccessMaskFromRights( FileSystemRights fileSystemRights, AccessControlType controlType ) { if (fileSystemRights < (FileSystemRights) 0 || fileSystemRights > FileSystemRights.FullControl) throw new ArgumentOutOfRangeException("fileSystemRights", Environment.GetResourceString("Argument_InvalidEnumValue", fileSystemRights, "FileSystemRights")); Contract.EndContractBlock(); if (controlType == AccessControlType.Allow) { fileSystemRights |= FileSystemRights.Synchronize; } else if (controlType == AccessControlType.Deny) { if (fileSystemRights != FileSystemRights.FullControl && fileSystemRights != (FileSystemRights.FullControl & ~FileSystemRights.DeleteSubdirectoriesAndFiles)) fileSystemRights &= ~FileSystemRights.Synchronize; } return ( int )fileSystemRights; } internal static FileSystemRights RightsFromAccessMask( int accessMask ) { return ( FileSystemRights )accessMask; } }
2.由于FileSystemAccessRule繼承自AccessRule,現(xiàn)在看一下AccessRule的源碼:
/// <summary> /// 表示用戶的標(biāo)識(shí)、訪問(wèn)掩碼和訪問(wèn)控制類型(允許或拒絕)的組合。<see cref="T:System.Security.AccessControl.AccessRule"/> 對(duì)象還包含有關(guān)子對(duì)象如何繼承規(guī)則以及如何傳播繼承的信息。 /// </summary> public abstract class AccessRule : AuthorizationRule { /// <summary> /// 使用指定的值初始化 <see cref="T:System.Security.AccessControl.AccessRule"/> 類的一個(gè)新實(shí)例。 /// </summary> /// <param name="identity">應(yīng)用訪問(wèn)規(guī)則的標(biāo)識(shí)。此參數(shù)必須是可以強(qiáng)制轉(zhuǎn)換為 <see cref="T:System.Security.Principal.SecurityIdentifier"/> 的對(duì)象。</param><param name="accessMask">此規(guī)則的訪問(wèn)掩碼。訪問(wèn)掩碼是一個(gè) 32 位的匿名位集合,其含義是由每個(gè)集成器定義的。</param><param name="isInherited">如果此規(guī)則繼承自父容器,則為 true。</param><param name="inheritanceFlags">訪問(wèn)規(guī)則的繼承屬性。</param><param name="propagationFlags">繼承的訪問(wèn)規(guī)則是否自動(dòng)傳播。如果 <paramref name="inheritanceFlags"/> 設(shè)置為 <see cref="F:System.Security.AccessControl.InheritanceFlags.None"/>,則將忽略傳播標(biāo)志。</param><param name="type">有效的訪問(wèn)控制類型。</param><exception cref="T:System.ArgumentException"><paramref name="identity"/> 參數(shù)的值不能強(qiáng)制轉(zhuǎn)換為 <see cref="T:System.Security.Principal.SecurityIdentifier"/>,或者 <paramref name="type"/> 參數(shù)包含無(wú)效值。</exception><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="accessMask"/> 參數(shù)的值為零,或者 <paramref name="inheritanceFlags"/> 或 <paramref name="propagationFlags"/> 參數(shù)包含無(wú)法識(shí)別的標(biāo)志值。</exception> protected AccessRule(IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type); /// <summary> /// 獲取與此 <see cref="T:System.Security.AccessControl.AccessRule"/> 對(duì)象關(guān)聯(lián)的 <see cref="T:System.Security.AccessControl.AccessControlType"/> 對(duì)象。 /// </summary> /// /// <returns> /// 與此 <see cref="T:System.Security.AccessControl.AccessRule"/> 對(duì)象關(guān)聯(lián)的 <see cref="T:System.Security.AccessControl.AccessControlType"/> 對(duì)象。 /// </returns> public AccessControlType AccessControlType { get; } }
看來(lái)DotNet中實(shí)現(xiàn)文件權(quán)限設(shè)置的操作的類,現(xiàn)在提供幾個(gè)具體的文件設(shè)置操作代碼:
3.獲取目錄權(quán)限列表:
/// <summary> /// 獲取目錄權(quán)限列表 /// </summary> /// <param name="path">目錄的路徑。</param> /// <returns>指示目錄的權(quán)限列表</returns> public IList<FileSystemRights> GetDirectoryPermission(string path) { try { if (!DirectoryExists(path)) return null; IList<FileSystemRights> result = new List<FileSystemRights>(); var dSecurity = Directory.GetAccessControl(new DirectoryInfo(path).FullName); foreach (FileSystemAccessRule rule in dSecurity.GetAccessRules(true, true, typeof(NTAccount))) result.Add(rule.FileSystemRights); return result; } catch (Exception e) { throw new Exception(e.Message, e); } }
4.設(shè)置目錄權(quán)限
/// <summary> ///設(shè)置目錄權(quán)限 /// </summary> /// <param name="path">目錄的路徑。</param> /// <param name="permission">在目錄上設(shè)置的權(quán)限。</param> /// <returns>指示是否在目錄上應(yīng)用權(quán)限的值。</returns> public bool SetDirectoryPermission(string path, FileSystemRights permission) { try { if (!DirectoryExists(path)) return false; var accessRule = new FileSystemAccessRule("Users", permission, InheritanceFlags.None, PropagationFlags.NoPropagateInherit, AccessControlType.Allow); var info = new DirectoryInfo(path); var security = info.GetAccessControl(AccessControlSections.Access); bool result; security.ModifyAccessRule(AccessControlModification.Set, accessRule, out result); if (!result) return false; const InheritanceFlags iFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit; accessRule = new FileSystemAccessRule("Users", permission, iFlags, PropagationFlags.InheritOnly, AccessControlType.Allow); security.ModifyAccessRule(AccessControlModification.Add, accessRule, out result); if (!result) return false; info.SetAccessControl(security); return true; } catch (Exception e) { throw new Exception(e.Message, e); } }
5.設(shè)置目錄權(quán)限列表
/// <summary> /// 設(shè)置目錄權(quán)限列表 /// </summary> /// <param name="path">目錄的路徑。</param> /// <param name="permissions">在目錄上設(shè)置的權(quán)限。</param> /// <returns>指示是否在目錄上應(yīng)用權(quán)限的值。</returns> public bool SetDirectoryPermissions(string path, FileSystemRights[] permissions) { try { if (!DirectoryExists(path) || permissions == null || !permissions.Any()) return false; foreach (var permission in permissions) if (!SetDirectoryPermission(path, permission)) return false; return true; } catch (Exception e) { throw new Exception(e.Message, e); } }
以上就是C#設(shè)置文件權(quán)限的方法的詳細(xì)內(nèi)容,更多關(guān)于C#設(shè)置文件權(quán)限的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- 采用C#代碼動(dòng)態(tài)設(shè)置文件權(quán)限
- c# 用Base64實(shí)現(xiàn)文件上傳
- c# 實(shí)現(xiàn)文件上傳下載功能的實(shí)例代碼
- c#添加圖片、文本水印到PDF文件
- C# 監(jiān)控 Windows 文件夾的方法
- C# 讀寫XML文件實(shí)例代碼
- C# protobuf自動(dòng)更新cs文件
- C#中將xml文件反序列化為實(shí)例時(shí)采用基類還是派生類的知識(shí)點(diǎn)討論
- C# http系列之以form-data方式上傳多個(gè)文件及鍵值對(duì)集合到遠(yuǎn)程服務(wù)器
- C#鎖住文件的操作步驟
- C#拷貝整個(gè)文件夾及子目錄和其中文件的方法
相關(guān)文章
如何使用C#修改本地Windows系統(tǒng)時(shí)間
這篇文章主要介紹了如何使用C#修改本地Windows系統(tǒng)時(shí)間,幫助大家更好的理解和使用c#,感興趣的朋友可以了解下2021-01-01關(guān)于C#?調(diào)用Dll?傳遞字符串指針參數(shù)的問(wèn)題
這篇文章主要介紹了C#?調(diào)用Dll傳遞字符串指針參數(shù),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-01-01解析C#中委托的同步調(diào)用與異步調(diào)用(實(shí)例詳解)
本篇文章是對(duì)C#中委托的同步調(diào)用與異步調(diào)用進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05C# SqlSugar批量執(zhí)行SQL語(yǔ)句及批量更新實(shí)體對(duì)象的操作方法
SqlSugar 是一款 老牌 .NET開源ORM框架,由果糖大數(shù)據(jù)科技團(tuán)隊(duì)維護(hù)和更新 ,開箱即用最易上手的ORM,這篇文章主要介紹了C# SqlSugar批量執(zhí)行SQL語(yǔ)句以及批量更新實(shí)體對(duì)象,需要的朋友可以參考下2024-07-07C#簡(jiǎn)單連接sql數(shù)據(jù)庫(kù)的方法
這篇文章主要介紹了C#簡(jiǎn)單連接sql數(shù)據(jù)庫(kù)的方法,涉及C#基于控制臺(tái)的數(shù)據(jù)庫(kù)連接創(chuàng)建于命令執(zhí)行相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2016-06-06