基本上,我需要在远程计算机上创建远程共享,并为特定用户授予此共享的访问权限 .

我需要信息 - credentials 用于远程计算机, unc 路径用于已存在的文件夹,我需要为其创建远程共享 . 我使用以下 func 在远程计算机上创建共享:

[DllImport("Netapi32.dll")]
private static extern uint NetShareAdd(
    [MarshalAs(UnmanagedType.LPWStr)] string strServer,
    Int32 dwLevel,
    ref SHARE_INFO_502 buf,
    out uint parm_err
);

在创建共享之前,我必须制作 impersonation

[DllImport("advapi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool LogonUser(
    string pszUserName,
    string pszDomain,
    IntPtr pszPassword,
    int dwLogonType,
    int dwLogonProvider,
    out IntPtr phToken);

实际上它运作良好 . 我的意思是远程共享已成功创建 . 但之后我需要授予访问权限 . 在这里我实际上有一个问题 .

所以所有步骤都是这样的:

getting sid
make impersonation
{
  creating share
  grant access()
}

我正在使用 sid 授予访问权限 . 我试图授予 everyone 访问权限并且有效 .

var sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);

//path is unc path here like "\\192.169.0.1\c$\myDirectory"
public static void GrantDirectoryAccess(SecurityIdentifier userSid, string path)
{
    var newAccessRule = return new FileSystemAccessRule(userSid,
                FileSystemRights.FullControl,
                InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit,
                PropagationFlags.None,
                AccessControlType.Allow);

    var dirInfo = new DirectoryInfo(path);
    directorySecurity = dirInfo.GetAccessControl(AccessControlSections.Access);
    directorySecurity.AddAccessRule(newAccessRule);           
    dirInfo.SetAccessControl(directorySecurity);           
}

但是我需要为运行应用程序的特定用户授予访问权限 . 我已经尝试过了:

var sid_1 = WindowsIdentity.GetCurrent().User.AccountDomainSid;
var sid_2 = System.DirectoryServices.AccountManagement.UserPrincipal.Current.Sid;

但它不起作用 . 没错 . 获得授权后无法访问 .