在 c# 中创建(主)文件夹并使用其他用户模拟设置文件夹权限

creating (home) folder and setting folder permissions with other user impersonation in c#

问题描述

我正在尝试使用我的程序创建活动目录用户。 所有与活动目录相关的部分都在工作。对我来说一个问题是模拟在我们的文件服务器上创建一个文件夹并设置适当的权限。 模拟的问题是软件需要使用多个管理帐户。因此,shift + rightclick -> 运行 as different user

不是解决方案

任务方法

所以我通常会如何处理它包括以下步骤:

  1. 使用对主驱动器文件夹具有适当权限的帐户登录
  2. 导航到“\FileServer\Data\Home”
  3. 为用户创建一个文件夹,如'\FileServer\Data\Home\exampleuser1'
  4. 为给定用户
  5. 设置适当的read/write权限

以编程方式,我会在(伪代码)行中做一些事情:

string path = "\FileServer\Data\Home\exampleuser1"
if (!Directory.Exists(path))
{
    Directory.Create(path);
    AddDirectorySecurity(path, @"MYDOMAIN\exampleuser1", FileSystemRights.TakeOwnership, AccessControlType.Allow);
}

但是,必须使用另一个用户帐户“domain\admin_julian”执行此代码“=11=]

已在此处找到答案: How to provide user name and password when connecting to a network share(来自 Luke Quinane 的回答)

实施他的 class 然后像这样使用它:

using (new NetworkConnection(@"\server\Data\Home", cred))
{
    string path = $@"\server\Data\Home\testuserfolder";
    string domainName = "domain.com";
    string userNameToCreate = "testuser";
    Directory.CreateDirectory(path);
    SetFullPermission(path, userNameToCreate);
}