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.CreateDirecto ry("T:\tem p\")
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?
I want that the user could create a directory only via the application that I'm making.
How to do :
IO.Directory.CreateDirecto
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?
ASKER
Could you translate to VB?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
here it is a script that should help you
using System.Security.Principal;
using System.Runtime.InteropServ
//the following code executed before you perform your task
if ( ! ImpersonationUtil.Imperson
{
MessageBox.Show("Impersona
return;
}
//Perform task as this user here...
//After your task, do this:
ImpersonationUtil.UnImpers
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 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(tokenDupli
impersonationContext = tempWindowsIdentity.Impers
if ( null != impersonationContext ) return true;
}
}
return false;
}
/// <summary>
/// Unimpersonate.
/// </summary>
public static void UnImpersonate() {
impersonationContext.Undo(
}
[DllImport("advapi32.dll",
public static extern int LogonUser(
string lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken );
[DllImport("advapi32.dll",
CharSet=System.Runtime.Int
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_CLEA
private const int LOGON32_PROVIDER_DEFAULT = 0;
private static WindowsImpersonationContex
}