/* * 实现文件系统管理功能封装。提供共享文件和文件系统访问权限控制能力。 * 来源:思海网络(http://www.thinksea.com/) */ namespace Thinksea.Windows.FileSystem { /// <summary> /// 共享资源类型。 /// </summary> public enum ShareResourceType : uint { /// <summary> /// 磁盘驱动器 /// </summary> DiskDrive = 0x0, PrintQueue = 0x1, Device = 0x2, IPC = 0x3, /// <summary> /// 为管理目的设置的磁盘驱动器共享。 /// </summary> DiskDriveAdmin = 0x80000000, PrintQueueAdmin = 0x80000001, DeviceAdmin = 0x80000002, IPCAdmin = 0x80000003 } /// <summary> /// 共享配置节。 /// </summary> public class Share { /// <summary> /// 共享的目录路径。 /// </summary> public string Path { get; set; } /// <summary> /// 共享名。 /// </summary> public string Name { get; set; } private string _Description = null; /// <summary> /// 注释。 /// </summary> public string Description { get { return this._Description; } set { this._Description = value; } } private ShareResourceType _Type = ShareResourceType.DiskDrive; /// <summary> /// 共享类型。 /// </summary> public ShareResourceType Type { get { return this._Type; } set { this._Type = value; } } private int _MaximumAllowed = 0; /// <summary> /// 允许连接的最大用户数量。取值为 0 表示允许最多用户连接;否则设置为正整数表示允许连接的用户数量限制。 /// </summary> public int MaximumAllowed { get { return this._MaximumAllowed; } set { this._MaximumAllowed = value; } } /// <summary> /// 一个构造方法。 /// </summary> /// <param name="Path">共享的目录路径。</param> /// <param name="Name">共享名。</param> public Share(string Path, string Name) { this.Path = Path; this.Name = Name; } /// <summary> /// 一个构造方法。 /// </summary> /// <param name="Path">共享的目录路径。</param> public Share(string Path) { this.Path = Path; this.Name = Path; } } /// <summary> /// 文件系统共享管理类。 /// </summary> /// <example> /// <code> /// //获取指定目录的安全性设置 ///string path = @"c:/testabc"; ///AccessManagement fspm = new AccessManagement(); ///AccessCollection dacl = fspm.GetPermission(path); ///foreach (var tmp in dacl) ///{ /// System.Console.WriteLine("[" + tmp.Domain + "]." + tmp.Name + ":" + tmp.SIDString); /// System.Console.WriteLine(" " + tmp.AccessMask.ToString()); /// System.Console.WriteLine(" " + tmp.AceFlags.ToString()); /// System.Console.WriteLine(" " + tmp.AceType.ToString()); ///} /// //允许用户 Everyone 持“完全访问权限”访问此目录。 ///dacl.Clear(); ///Access ace = new Access(); ///ace.Name = "Everyone"; ///ace.AccessMask = AccessPrivileges.AllAccess; ///ace.AceType = AccessType.AccessAllowed; ///dacl.Add(ace); ///fspm.SetPermission(path, dacl); /// </code> /// </example> public class ShareManagement { /// <summary> /// 获取指定名称的共享。 /// </summary> /// <param name="ShareName">共享名称。</param> /// <returns>共享信息。找不到返回 null。</returns> public Share GetShare(string ShareName) { ShareName = ShareName.ToLower(); System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher("SELECT * FROM Win32_share"); foreach (System.Management.ManagementObject share in searcher.Get()) { if (((string)share.GetPropertyValue("Name")).ToLower() == ShareName) { Share s = new Share((string)share.GetPropertyValue("Path"), (string)share.GetPropertyValue("Name")); s.Description = (string)share.GetPropertyValue("Description"); s.Type = (ShareResourceType)share.GetPropertyValue("Type"); if ((bool)share.GetPropertyValue("AllowMaximum")) { s.MaximumAllowed = 0; } else { s.MaximumAllowed = System.Convert.ToInt32(share.GetPropertyValue("MaximumAllowed")); } return s; } } return null; } /// <summary> /// 获取全部的共享信息。 /// </summary> /// <returns>共享信息集合。</returns> public Share[] GetShares() { System.Collections.Generic.List<Share> l = new System.Collections.Generic.List<Share>(); System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher("SELECT * FROM Win32_share"); foreach (System.Management.ManagementObject share in searcher.Get()) { Share s = new Share((string)share.GetPropertyValue("Path"), (string)share.GetPropertyValue("Name")); s.Description = (string)share.GetPropertyValue("Description"); s.Type = (ShareResourceType)share.GetPropertyValue("Type"); if ((bool)share.GetPropertyValue("AllowMaximum")) { s.MaximumAllowed = 0; } else { s.MaximumAllowed = System.Convert.ToInt32(share.GetPropertyValue("MaximumAllowed")); } l.Add(s); //l.Add(share.GetText(System.Management.TextFormat.Mof)); } return l.ToArray(); } /// <summary> /// 判断指定的共享是否存在。 /// </summary> /// <param name="ShareName">共享名称。</param> /// <returns>存在返回 true;否则返回 false。</returns> public bool IsExistsShare(string ShareName) { ShareName = ShareName.ToLower(); System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher("SELECT * FROM Win32_share"); foreach (System.Management.ManagementObject share in searcher.Get()) { if (((string)share.GetPropertyValue("Name")).ToLower() == ShareName) { return true; } } return false; } /// <summary> /// 为指定的目录开启共享设置。 /// </summary> /// <param name="sre">共享配置节</param> public void CreateShare(Share sre) { System.Management.ManagementClass mc = new System.Management.ManagementClass("win32_share"); System.Management.ManagementBaseObject inParams = mc.GetMethodParameters("Create"); inParams["Path"] = sre.Path; inParams["Name"] = sre.Name; inParams["Type"] = sre.Type; if (sre.MaximumAllowed == 0) { inParams["MaximumAllowed"] = null; //null = 用户数连接无限制,否则指定一个正整数 } else { inParams["MaximumAllowed"] = sre.MaximumAllowed; //null = 用户数连接无限制,否则指定一个正整数 } inParams["Description"] = sre.Description; inParams["Password"] = null; inParams["Access"] = null; //null = 使Everyone拥有完全控制权限 System.Management.ManagementBaseObject outParams = mc.InvokeMethod("Create", inParams, null); switch ((uint)outParams.Properties["ReturnValue"].Value) { case 0: //Success break; case 2: //Access denied throw new System.Exception("无权访问"); case 8: //Unknown failure throw new System.Exception("未知失败"); case 9: //Invalid name throw new System.Exception("非法的共享名"); case 10: //Invalid level throw new System.Exception("非法的层次"); case 21: //Invalid parameter throw new System.Exception("非法的参数"); case 22: //Duplicate share throw new System.Exception("重复共享"); case 23: //Redirected path throw new System.Exception("重定向路径"); case 24: //Unknown device or directory throw new System.Exception("未知的目录"); case 25: //Net name not found throw new System.Exception("网络名不存在"); default: throw new System.Exception("未知异常信息"); } } /// <summary> /// 取消共享指定目录。 /// </summary> /// <param name="ShareName">共享名称。</param> public void DeleteShare(string ShareName) { System.Management.ManagementObject classInstance = new System.Management.ManagementObject(@"root/CIMV2", "Win32_Share.Name='" + ShareName + @"'", null); System.Management.ManagementBaseObject outParams = classInstance.InvokeMethod("Delete", null, null); switch ((uint)outParams.Properties["ReturnValue"].Value) { case 0: //Success break; case 2: //Access denied throw new System.Exception("无权访问"); case 8: //Unknown failure throw new System.Exception("未知失败"); case 9: //Invalid name throw new System.Exception("非法的共享名"); case 10: //Invalid level throw new System.Exception("非法的层次"); case 21: //Invalid parameter throw new System.Exception("非法的参数"); case 22: //Duplicate share throw new System.Exception("重复共享"); case 23: //Redirected path throw new System.Exception("重定向路径"); case 24: //Unknown device or directory throw new System.Exception("未知的目录"); case 25: //Net name not found throw new System.Exception("网络名不存在"); default: throw new System.Exception("未知异常信息"); } } } /// <summary> /// 访问权限描述。 /// </summary> [System.Flags] public enum AccessPrivileges : uint { /// <summary> /// 列出文件夹/读取数据 /// </summary> FileReadData = 0x00000001, /// <summary> /// 创建文件/写入数据 /// </summary> FileWriteData = 0x00000002, /// <summary> /// 创建文件夹/附加数据 /// </summary> FileAppendData = 0x00000004, /// <summary> /// 读取扩展属性 /// </summary> FileReadEA = 0x00000008, /// <summary> /// 写入扩展属性 /// </summary> FileWriteEA = 0x00000010, /// <summary> /// 遍历文件夹/运行文件 /// </summary> FileExecute = 0x00000020, /// <summary> /// 删除子文件夹及文件。 /// </summary> FileDeleteChild = 0x00000040, /// <summary> /// 读取属性 /// </summary> FileReadAttributes = 0x00000080, /// <summary> /// 写入属性 /// </summary> FileWriteAttributes = 0x00000100, /// <summary> /// 删除 /// </summary> Delete = 0x00010000, /// <summary> /// 读取权限 /// </summary> ReadControl = 0x00020000, /// <summary> /// 更改权限 /// </summary> WriteDac = 0x00040000, /// <summary> /// 取得所有权 /// </summary> WriteOwner = 0x00080000, /// <summary> /// 完全控制 /// </summary> AllAccess = FileReadData | FileWriteData | FileAppendData | FileReadEA | FileWriteEA | FileExecute | FileDeleteChild | FileReadAttributes | FileWriteAttributes | Delete | ReadControl | WriteDac | WriteOwner | Synchronize, /// <summary> /// 同步 /// </summary> Synchronize = 0x00100000, /// <summary> /// 未知属性(此值保留备用)。 /// </summary> Unknown = 0x10000000, } /// <summary> /// 指示访问权限应用范围。 /// </summary> [System.Flags] public enum AccessFlags : uint { /// <summary> /// 无。 /// </summary> NonInheritAce = 0, /// <summary> /// 该文件夹及文件 /// </summary> ObjectInheritAce = 1, /// <summary> /// 该文件夹及子文件夹 /// </summary> ContainerInheritAce = 2, /// <summary> /// 将这些权限只应用到这个容器中的对象和/容器上 /// </summary> /// <remarks> /// 其实这也是继承访问权限的,如果设置此项,则向文件和子文件夹传播刚才设置的特殊访问权限;如果清除选择,则阻止权限的继承。 /// </remarks> NoPropagateInheritAce = 4, InheritOnlyAce = 8, InheritedAce = 16 } /// <summary> /// 权限作用类型。 /// </summary> [System.Flags] public enum AccessType : uint { /// <summary> /// 允许 /// </summary> AccessAllowed = 0, /// <summary> /// 否认 /// </summary> AccessDenied = 1, /// <summary> /// 审核 /// </summary> Audit = 2 } /// <summary> /// 访问权限设置配置节。 /// </summary> public class Access { internal string _SIDString = ""; /// <summary> /// ID /// </summary> public string SIDString { get { return this._SIDString; } } /// <summary> /// 用户/组名称。 /// </summary> public string Name { get; set; } private string _Domain = null; /// <summary> /// 域。 /// </summary> public string Domain { get { return this._Domain; } set { this._Domain = value; } } /// <summary> /// 访问权限 /// </summary> public AccessPrivileges AccessMask { get; set; } private AccessFlags _AceFlags = AccessFlags.ObjectInheritAce | AccessFlags.ContainerInheritAce; /// <summary> /// 访问权限应用范围。 /// </summary> public AccessFlags AceFlags { get { return this._AceFlags; } set { this._AceFlags = value; } } private AccessType _AceType = AccessType.AccessAllowed; /// <summary> /// 权限作用类型。 /// </summary> public AccessType AceType { get { return this._AceType; } set { this._AceType = value; } } } /// <summary> /// 访问权限设置集合。 /// </summary> public class AccessCollection : System.Collections.Generic.ICollection<Access> { /// <summary> /// 权限集合。 /// </summary> private System.Collections.Generic.List<Access> DaclCollection = new System.Collections.Generic.List<Access>(); /// <summary> /// 为此集合对象提供索引访问。 /// </summary> /// <param name="index"></param> /// <returns></returns> public Access this[int index] { get { return this.DaclCollection[index]; } } #region ICollection<Access> 成员 /// <summary> /// 将对象添加到集合的结尾处。 /// </summary> /// <param name="item"></param> public void Add(Access item) { this.DaclCollection.Add(item); } /// <summary> /// 从集合中移除所有元素。 /// </summary> public void Clear() { this.DaclCollection.Clear(); } /// <summary> /// 确定指定的元素是否在集合中。 /// </summary> /// <param name="item"></param> /// <returns></returns> public bool Contains(Access item) { return this.DaclCollection.Contains(item); } /// <summary> /// 将整个集合复制到兼容的一维数组中,从目标数组的指定索引位置开始放置。 /// </summary> /// <param name="array"></param> /// <param name="arrayIndex"></param> public void CopyTo(Access[] array, int arrayIndex) { this.DaclCollection.CopyTo(array, arrayIndex); } /// <summary> /// 获取集合中实际包含的元素数。 /// </summary> public int Count { get { return this.DaclCollection.Count; } } /// <summary> /// 获取一个值,判断集合是否为只读。 /// </summary> public bool IsReadOnly { get { return false; } } /// <summary> /// 从集合中移除特定对象的第一个匹配项。 /// </summary> /// <param name="item"></param> /// <returns></returns> public bool Remove(Access item) { return this.DaclCollection.Remove(item); } #endregion #region IEnumerable<Access> 成员 /// <summary> /// 返回循环访问集合的枚举数。 /// </summary> /// <returns></returns> public System.Collections.Generic.IEnumerator<Access> GetEnumerator() { return this.DaclCollection.GetEnumerator(); } #endregion #region IEnumerable 成员 System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.DaclCollection.GetEnumerator(); } #endregion } /// <summary> /// 文件系统权限管理类。 /// </summary> /// <example> /// <code> ///string path = @"c:/testabc"; ///ShareManagement fss = new ShareManagement(); /// //如果存在指定共享则删除 ///if (fss.IsExistsShare(path)) ///{ /// fss.DeleteShare(path); ///} /// /// //创建共享 ///Share sre = new Share(path); ///sre.MaximumAllowed = 0; ///fss.CreateShare(sre); /// /// //获取全部的共享 ///foreach (Share tmp in fss.GetShares()) ///{ /// System.Console.WriteLine(tmp.Name + ":" + tmp.Type.ToString()); ///} /// </code> /// </example> public class AccessManagement { /// <summary> /// 一个构造方法。 /// </summary> public AccessManagement() { } /// <summary> /// 获取一个 WMI 操作对象。 /// </summary> /// <param name="FilePath">文件/目录路径。</param> /// <returns></returns> private System.Management.ManagementObject GetManagementObject(string FilePath) { //ManagementPath path = new ManagementPath(); //path.Server = "."; // 机器名, .表示本机 //path.NamespacePath = @"root/CIMV2"; //path.RelativePath = string.Format("Win32_LogicalFileSecuritySetting.Path='{0}'", FilePath); //ManagementObject mo = new ManagementObject(path); return new System.Management.ManagementObject(string.Format("Win32_LogicalFileSecuritySetting.Path='{0}'", FilePath)); } /// <summary> /// 获取指定文件或目录的访问权限设置。 /// </summary> /// <param name="FilePath">文件/目录路径。</param> /// <returns></returns> /// <exception cref="System.Exception">无权访问;未知失败;缺少权限;非法的参数</exception> public AccessCollection GetPermission(string FilePath) { if (!System.IO.File.Exists(FilePath) && !System.IO.Directory.Exists(FilePath)) { throw new System.IO.FileNotFoundException("指定的文件或目录不存在。", FilePath); } AccessCollection dacl = new AccessCollection(); System.Management.ManagementObject mo = this.GetManagementObject(FilePath); System.Management.ManagementBaseObject outParams = mo.InvokeMethod("GetSecurityDescriptor", null, null); //if ((uint)outParams.Properties["ReturnValue"].Value != 0) //{ // return null; //} switch ((uint)outParams.Properties["ReturnValue"].Value) { case 0: //Success break; case 2: //Access denied throw new System.Exception("无权访问"); case 8: //Unknown failure throw new System.Exception("未知失败"); case 9: //Privilege missing throw new System.Exception("缺少权限"); case 21: //Invalid parameter throw new System.Exception("非法的参数"); default: throw new System.Exception("未知异常信息"); } System.Management.ManagementBaseObject Descriptor = (System.Management.ManagementBaseObject)outParams.Properties["Descriptor"].Value; foreach (System.Management.ManagementBaseObject mbo in (System.Management.ManagementBaseObject[])Descriptor.Properties["Dacl"].Value) { Access ace = new Access(); ace.AccessMask = (AccessPrivileges)mbo["AccessMask"]; ace.AceFlags = (AccessFlags)mbo["AceFlags"]; ace.AceType = (AccessType)mbo["AceType"]; System.Management.ManagementBaseObject Trustee = ((System.Management.ManagementBaseObject)(mbo["Trustee"])); ace.Name = (string)Trustee.Properties["Name"].Value; ace.Domain = (string)Trustee.Properties["Domain"].Value; ace._SIDString = (string)Trustee.Properties["SIDString"].Value; dacl.Add(ace); } return dacl; } /// <summary> /// 设置指定文件或目录的访问权限设置。 /// </summary> /// <param name="FilePath">文件/目录路径。</param> /// <param name="dacl">权限组。</param> public void SetPermission(string FilePath, AccessCollection dacl) { if (!System.IO.File.Exists(FilePath) && !System.IO.Directory.Exists(FilePath)) { throw new System.IO.FileNotFoundException("指定的文件或目录不存在。", FilePath); } System.Management.ManagementObject mo = this.GetManagementObject(FilePath); System.Management.ManagementBaseObject outParams = mo.InvokeMethod("GetSecurityDescriptor", null, null); switch ((uint)outParams.Properties["ReturnValue"].Value) { case 0: //Success break; case 2: //Access denied throw new System.Exception("无权访问"); case 8: //Unknown failure throw new System.Exception("未知失败"); case 9: //Privilege missing throw new System.Exception("缺少权限"); case 21: //Invalid parameter throw new System.Exception("非法的参数"); default: throw new System.Exception("未知异常信息"); } System.Collections.Generic.List<System.Management.ManagementBaseObject> newDacl = new System.Collections.Generic.List<System.Management.ManagementBaseObject>(); foreach (var tmp in dacl) { //增加用户 System.Management.ManagementClass trustee = new System.Management.ManagementClass("win32_trustee"); trustee.Properties["Name"].Value = tmp.Name; trustee.Properties["Domain"].Value = tmp.Domain; //设置权限 System.Management.ManagementClass ace = new System.Management.ManagementClass("win32_ace"); ace.Properties["AccessMask"].Value = tmp.AccessMask; ace.Properties["AceFlags"].Value = tmp.AceFlags; ace.Properties["AceType"].Value = tmp.AceType; ace.Properties["Trustee"].Value = trustee; newDacl.Add(ace); } System.Management.ManagementBaseObject Descriptor = (System.Management.ManagementBaseObject)outParams.Properties["Descriptor"].Value; Descriptor.Properties["Dacl"].Value = newDacl.ToArray(); //Descriptor.Properties["Group"].Value = null; //Descriptor.Properties["Owner"].Value = null; System.Management.ManagementBaseObject inParams = mo.GetMethodParameters("SetSecurityDescriptor"); inParams["Descriptor"] = Descriptor; System.Management.ManagementBaseObject ret = mo.InvokeMethod("SetSecurityDescriptor", inParams, null); switch ((uint)ret.Properties["ReturnValue"].Value) { case 0: //Success break; case 2: //Access denied throw new System.Exception("无权访问"); case 8: //Unknown failure throw new System.Exception("未知失败"); case 9: //Privilege missing throw new System.Exception("缺少权限"); case 21: //Invalid parameter throw new System.Exception("非法的参数"); default: throw new System.Exception("未知异常信息"); } } } }
[WMI实例]实现文件系统管理功能封装。提供共享文件和文件系统访问权限控制能力
最新推荐文章于 2024-04-24 14:26:05 发布