在this link中,输出22表示重复共享。
我正在尝试通过c#执行以下操作:创建用户并将其添加到共享文件夹,我的意思是:
但是我得到输出22,因为共享已经存在,我只想添加另一个用户到现有共享文件夹中,我的问题:如何添加用户通过c#访问现有共享?
这里有一个创建用户的方法,它工作正常:
private static void CreateUser(string uName , string password)
{
try
{
PrincipalContext ctx = new PrincipalContext(ContextType.Machine);
UserPrincipal user = new UserPrincipal(ctx , uName , password, true);
user.PasswordNeverExpires = true;
user.Save();
} catch
{
Console.WriteLine("account already exist");
}
}
这里有一个创建共享并将其绑定到用户的方法,当共享存在时返回22,如果不存在则返回0并创建新共享并将其绑定到用户:
private static uint AddAnotherUserToSHaredFolder(string uName , string sharedPath , string shareName , string description)
{
DirectoryInfo dInfo = new DirectoryInfo(sharedPath);
WindowsIdentity id = WindowsIdentity.GetCurrent();
DirectorySecurity dSecurity = dInfo.GetAccessControl();
dSecurity.AddAccessRule(new FileSystemAccessRule(uName , FileSystemRights.FullControl , InheritanceFlags.ContainerInherit , PropagationFlags.InheritOnly , AccessControlType.Allow));
dInfo.SetAccessControl(dSecurity);
//Gets User SID for share permissions **NotSecurty**
NTAccount account = new NTAccount(System.Environment.MachineName , uName);
SecurityIdentifier sid = (SecurityIdentifier)account.Translate(typeof(SecurityIdentifier));
byte[] sidArray = new byte[sid.BinaryLength];
sid.GetBinaryForm(sidArray , 0);
ManagementObject Trustee = new ManagementClass("root\\CIMV2" , "Win32_Trustee" , null);
Trustee["Domain"] = ".";
Trustee["Name"] = uName;
Trustee["SID"] = sidArray;
ManagementBaseObject AdminACE = new ManagementClass(new ManagementPath("Win32_Ace") , null);
// Add the input parameters.
AdminACE["AccessMask"] = 2032127;
AdminACE["AceFlags"] = 3;
AdminACE["AceType"] = 0;
AdminACE["Trustee"] = Trustee;
//Security Descriptor For Share creation Parameter
ManagementObject secDescriptor = new ManagementClass(new ManagementPath("Win32_SecurityDescriptor") , null);
secDescriptor["ControlFlags"] = 4;
secDescriptor["DACL"] = new object[] { AdminACE };
ManagementClass classInstance = new ManagementClass("root\\CIMV2" , "Win32_Share" , null);
// Obtain in-parameters for the method
ManagementBaseObject inParams = classInstance.GetMethodParameters("Create");
// Add the input parameters.
inParams["Name"] = shareName;
inParams["Path"] = sharedPath;
inParams["Type"] = 0;
inParams["Description"] = description;
inParams["Access"] = secDescriptor;
inParams["MaximumAllowed"] = null;
// Execute the method and obtain the return values.
ManagementBaseObject outParams = classInstance.InvokeMethod("Create" , inParams , null);
return (uint)(outParams.Properties["ReturnValue"].Value);
}
主要内容:
static void Main(string[] args)
{
string uName = "someUser";
string pass = "Aa12345#";
string path = @"C:\Users\me\Desktop\A";
string shareName = "MyShare";
string description = "some description";
CreateUser(uName , pass);
uint num = AddAnotherUserToSHaredFolder(uName , path , shareName , description);
Console.WriteLine(num);// output 22
}