Link to home
Start Free TrialLog in
Avatar of cpx_Support
cpx_Support

asked on

I want the code do actions as another user

To prevent accidental creation or deletetios of folders I restricted some rights to the users.
I want that the user could create a directory only via the application that I'm making.

How to do :  

IO.Directory.CreateDirectory("T:\temp\")

but in administrators rights.
Can I put somewere the user name and the password in the code to execute the code like it was the administrator?
Avatar of sognoct
sognoct
Flag of Italy image

remember to set   _userName, _password, _domain

here it is a script that should help you



using System.Security.Principal;
using System.Runtime.InteropServices;


//the following code executed before you perform your task

if ( ! ImpersonationUtil.Impersonate( _userName, _password, _domain ) )

{
MessageBox.Show("Impersonation failed.");
return;
}

//Perform task as this user here...

//After your task, do this:
ImpersonationUtil.UnImpersonate();


Here is the code for the ImpersonationUtil class:

/// <summary>
/// Impersonate a windows logon.
/// </summary>
public class ImpersonationUtil {

/// <summary>
/// Impersonate given logon information.
/// </summary>
/// <param name="logon">Windows logon name.</param>
/// <param name="password">password</param>
/// <param name="domain">domain name</param>
/// <returns></returns>
public static bool Impersonate( string logon, string password, string
domain ) {
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;

if( LogonUser( logon, domain, password, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref token) != 0 ) {

if ( DuplicateToken( token, 2, ref tokenDuplicate ) != 0 ) {
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
if ( null != impersonationContext ) return true;
}
}

return false;
}

/// <summary>
/// Unimpersonate.
/// </summary>
public static void UnImpersonate() {
impersonationContext.Undo();
}

[DllImport("advapi32.dll", CharSet=CharSet.Auto)]
public static extern int LogonUser(
string lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken );

[DllImport("advapi32.dll",
CharSet=System.Runtime.InteropServices.CharSet.Aut o,
SetLastError=true)]
public extern static int DuplicateToken(
IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken );

private const int LOGON32_LOGON_INTERACTIVE = 2;
private const int LOGON32_LOGON_NETWORK_CLEARTEXT = 4;
private const int LOGON32_PROVIDER_DEFAULT = 0;
private static WindowsImpersonationContext impersonationContext;
}
Avatar of cpx_Support
cpx_Support

ASKER

Could you translate to VB?
ASKER CERTIFIED SOLUTION
Avatar of sognoct
sognoct
Flag of Italy image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial