我如何使用不同的用户ID Directory.CreateDirectory? [英] How can I use Directory.CreateDirectory with a different user id?

查看:129
本文介绍了我如何使用不同的用户ID Directory.CreateDirectory?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编写代码以编程方式在我的工作站上的应用程序上创建一个目录(并执行其他文件操作) - 使用Directory.CreateDirectory这将很容易,我知道如何做到这一点。但是,问题是,我正试图做一个服务器上,我的用户ID没有权利这样做。我有一个A / D用户ID来做到这一点,但我不知道如何在我的应用程序中使用它来做我需要做的事情( impersonation 不是它所谓的,但是...)。

下面是我想要做的:

  System.Security.AccessControl.DirectorySecurity ds = new System.Security.AccessControl.DirectorySecurity(); 

//< - 这里发生了一些魔术 - >

Directory.CreateDirectory(@\\ofmsws42\c $ \New_Directory,ds);

魔术发生在哪里?还是我吠叫错了树?我想说,我的服务器证书最终在我创建的DirectorySecurity对象的某个地方,但DirectorySecurity的任何属性似乎都没有办法做到这一点。

解决方案

.microsoft.com / en-us / library / chf6fbt4.aspxrel =nofollow noreferrer> WindowsIdentity.Impersonate has sample(引用自SO:你如何在.NET中进行模拟?



以下是最重要的代码块( LogonUser 是从advapi32.dll中的PInvoke):

$ p $ // Call LogonUser获取处理访问令牌。
布尔的returnValue = LogonUser的(用户名,域名,到Console.ReadLine(),
LOGON32_LOGON_INTERACTIVE,LOGON32_PROVIDER_DEFAULT,
OUT safeTokenHandle);

。使用(WindowsImpersonationContext impersonatedUser =
WindowsIdentity.Impersonate(safeTokenHandle.DangerousGetHandle()))
{
...
}


I am trying to write code to programmatically create a directory (and do other file manipulations) on a server from an application on my workstation -- using Directory.CreateDirectory this would be easy enough, and I know how to do that. HOWEVER, the problem is that I am trying to do this on a server where my user id doesn't have rights to do so. I do have an A/D user id to do it with, but I am clueless as to how to use it in my application to do what I need to do (impersonation isn't what it's called, but...).

Here's what I am trying to do:

System.Security.AccessControl.DirectorySecurity ds = new System.Security.AccessControl.DirectorySecurity();

// <-- something magic happens here -->

Directory.CreateDirectory(@"\\ofmsws42\c$\New_Directory", ds);

What goes into the spot where the "magic" happens? Or am I barking up the wrong tree? I want to say that my credentials for the server end up somewhere in the DirectorySecurity object I am creating, but none of the properties of DirectorySecurity appear to do the trick.

解决方案

You need to impersonate with the account that have permissions in "magic code".

WindowsIdentity.Impersonate have sample (referenced from SO: How do you do Impersonation in .NET?)

Here are most important chunks of code (LogonUser is PInvoke from advapi32.dll):

// Call LogonUser to obtain a handle to an access token.
bool returnValue = LogonUser(userName, domainName, Console.ReadLine(),
      LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
      out safeTokenHandle);

using (WindowsImpersonationContext impersonatedUser = 
   WindowsIdentity.Impersonate(safeTokenHandle.DangerousGetHandle()))
{
...
}

这篇关于我如何使用不同的用户ID Directory.CreateDirectory?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆