hi.
i am using impersonateValidUser(i will paste my code in the following) to access a folder.i've FINISHED DEVELOPMENT OF PROGRAM and i've DEPLOY and INSTALL on some people's PC.
for some "good" PC it works well,but for some "bad" PC,only if i login with administrator's account it works well,otherwise "Access to the path 'xxx' is denied." is told.but for impersonateValidUser part it works works well. for these "bad" PC,if i dont use impersonateValidUser it works,it can access the folder.
i would like to ask ur help how could i fix the problem.thank u very much for u r kindness help in advance.
my code is:public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_PROVIDER_DEFAULT = 0;
WindowsImpersonationContext impersonationContext;
[DllImport("advapi32.dll")]
public static extern int LogonUserA(String lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int DuplicateToken(IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool RevertToSelf();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);
private void undoImpersonation()
{
impersonationContext.Undo();
}
private bool impersonateValidUser(String userName, String domain, String password)
{
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if (RevertToSelf())
{
if (LogonUserA(userName, 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 (impersonationContext != null)
{
CloseHandle(token);
CloseHandle(tokenDuplicate);
MessageBox.Show("return true");
return true;
}
}
}
}
if (token != IntPtr.Zero)
CloseHandle(token);
if (tokenDuplicate != IntPtr.Zero)
CloseHandle(tokenDuplicate);
return false;
}
private void button1_Click(object sender, EventArgs e)
{
if (impersonateValidUser("username", "domain", "psw"))
{
if (!Directory.Exists(rootComplete))
{
Directory.CreateDirectory(rootComplete);
}
File.Copy(filePath, doc, true);
undoImpersonation();
}
else
{
MessageBox.Show("impersonateValidUser,fail login.");
}
}