2012-07-11 76 views
1

我想編寫代碼以編程方式在我的工作站上的應用程序上創建一個目錄(並執行其他文件操作) - 使用Directory.CreateDirectory這很容易,我知道該怎麼做。但是,問題是我試圖在服務器上執行此操作,而我的用戶標識沒有權限這樣做。我有一個A/D用戶ID來做到這一點,但我不知道如何在我的應用程序中使用它來做我需要做的事情(模擬不是它所謂的,但是...) 。如何使用具有不同用戶標識的Directory.CreateDirectory?

這裏就是我想要做的:

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

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

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

什麼進入其中的「魔術」發生的地方?還是我吠叫錯了樹?我想說,我的服務器證書最終會在我創建的DirectorySecurity對象的某個地方出現,但是DirectorySecurity的任何屬性似乎都無能爲力。

回答

3

您需要模仿具有「魔術代碼」權限的帳戶。

WindowsIdentity.Impersonate有樣品(從SO引用:How do you do Impersonation in .NET?

以下是代碼最重要的組塊(LogonUser是PInvoke的從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())) 
{ 
... 
} 
相關問題