I am trying to get a token programitcally to access windows server's shared folder but i get this exception: The specified network password is not correct
This is the impersonation class:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices; // DllImport
using System.Security.Principal; // WindowsImpersonationContext
using System.Security.Permissions; // PermissionSetAttribute
namespace Impersonate
{
public class clsImpersonate
{
#region 'Impersonation'
// obtains user token
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(string pszUsername, string pszDomain, string pszPassword,
int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
// closes open handes returned by LogonUser
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);
public IntPtr ImpersonateUser(string sUsername, string sDomain, string sPassword)
{
// initialize token
IntPtr pExistingTokenHandle = new IntPtr(0);
// if domain name was blank, assume local machine
if (sDomain == "")
sDomain = System.Environment.MachineName;
try
{
string sResult = null;
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
// get handle to token
bool bImpersonated = LogonUser(sUsername, sDomain, sPassword,
LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref pExistingTokenHandle);
// did impersonation fail?
if (false == bImpersonated)
{
int nErrorCode = Marshal.GetLastWin32Error();
sResult = "LogonUser() failed with error code: " + nErrorCode + "\r\n";
// show the reason why LogonUser failed
//MessageBox.Show(sResult, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
// Get identity before impersonation
sResult += "Before impersonation: " + WindowsIdentity.GetCurrent().Name + "\r\n";
return pExistingTokenHandle;
}
catch (Exception ex)
{
throw ex;
}
}
public bool FreeImpersonationResource(IntPtr _token)
{
// close handle(s)
if (_token != IntPtr.Zero)
return CloseHandle(_token);
else return true;
}
#endregion
}
}
And this where i am using instance of this class:
private void buttonLogon_Click(object sender, System.EventArgs e)
{
clsImpersonate cls = new clsImpersonate();
IntPtr token = cls.ImpersonateUser(textBoxUsername.Text, textBoxDomain.Text, textBoxPassword.Text);
using (WindowsImpersonationContext impersonatedUser = WindowsIdentity.Impersonate(token))
{
string fileName = @"\\server\share\New Text Document.txt";
Process process = new Process();
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = fileName;
process.StartInfo = info;
process.Start();
}
cls.FreeImpersonationResource(token);