权限定义:
[Flags]
public enum AccessPrivileges : uint{
FILE_READ_DATA = 0x00000001,
FILE_WRITE_DATA = 0x00000002,
FILE_APPEND_DATA = 0x00000004,
FILE_READ_EA = 0x00000008,
FILE_WRITE_EA = 0x00000010,
FILE_EXECUTE = 0x00000020,
FILE_DELETE_CHILD = 0x00000040,
FILE_READ_ATTRIBUTES = 0x00000080,
FILE_WRITE_ATTRIBUTES = 0x00000100,
DELETE = 0x00010000,
READ_CONTROL = 0x00020000,
WRITE_DAC = 0x00040000,
WRITE_OWNER = 0x00080000,
SYNCHRONIZE = 0x00100000,
ACCESS_SYSTEM_SECURITY = 0x01000000,
MAXIMUM_ALLOWED = 0x02000000,
GENERIC_ALL = 0x10000000,
GENERIC_EXECUTE= 0x20000000,
GENERIC_WRITE = 0x40000000,
GENERIC_READ = 0x80000000
}
[Flags]
enum AceFlags : uint{
NonInheritAce = 0,
ObjectInheritAce = 1,
ContainerInheritAce = 2,
NoPropagateInheritAce = 4,
InheritOnlyAce = 8,
InheritedAce = 16
}
[Flags]
enum AceType : uint{
AccessAllowed = 0,
AccessDenied = 1,
Audit = 2
}
流程:
//设置Everyone用户,可以选择其他用户或新建用户
ManagementClass trustee = new ManagementClass("Win32_Trustee");
trustee.Properties["Name"].Value = "Everyone";
trustee.Properties["Domain"].Value = null;
trustee.Properties["SID"].Value = new byte[]{1,1,0,0,0,0,0,1,0,0,0,0};
//设置只读/运行权限
ManagementClass ace = new ManagementClass("Win32_ACE");
ace.Properties["AccessMask"].Value = AccessPrivileges.GENERIC_READ
| AccessPrivileges.FILE_READ_DATA | AccessPrivileges.FILE_READ_ATTRIBUTES | AccessPrivileges.FILE_READ_EA
| AccessPrivileges.READ_CONTROL | AccessPrivileges.FILE_EXECUTE;
ace.Properties["AceFlags"].Value = 3;//AceFlags.ObjectInheritAce | AceFlags.ContainerInheritAce ;
ace.Properties["AceType"].Value = 0;//AceType.AccessAllowed;
ace.Properties["Trustee"].Value = trustee;
//修改ACL设置
ManagementObject secDescriptor = new ManagementClass("Win32_SecurityDescriptor");
secDescriptor["ControlFlags"] = 4;
secDescriptor["DACL"] = new ManagementObject[] { ace };
//设置添加共享
ManagementClass mc = new ManagementClass("win32_share");
ManagementBaseObject inParams = mc.GetMethodParameters("Create");
inParams["Path"] = "f:\\dannyr";
inParams["Name"] = "share of dannyr";
inParams["Type"] = 0x0;
inParams["MaximumAllowed"] = null; //=null 则用户数连接无限制
inParams["Description"] = null;
inParams["Password"] = null;
inParams["Access"] = secDescriptor; //=null 则使Everyone拥有完全控制权限
ManagementBaseObject outParams = mc.InvokeMethod("Create", inParams, null);
uint returnValue = (uint)outParams.Properties["ReturnValue"].Value;
string ErrorMessage = null;
switch (returnValue)
{
case 0: //Success
break;
case 2: //Access denied
ErrorMessage = "无权访问";
break;
case 8: //Unknown failure
ErrorMessage = "未知错误";
break;
case 9: //Invalid name
ErrorMessage = "非法的共享名";
break;
case 10: //Invalid level
ErrorMessage = "非法的层次";
break;
case 21: //Invalid parameter
ErrorMessage = "非法的参数";
break;
case 22: //Duplicate share
ErrorMessage = "重复共享";
break;
case 23: //Redirected path
ErrorMessage = "重定向路径";
break;
case 24: //Unknown device or directory
ErrorMessage = "未知的目录";
break;
case 25: //Net name not found
ErrorMessage = "网络名不存在";
break;
default:
break;
}