I have a weird scenario here. My app connects to a fileserver to list the files from a directory using UNC. It has been working for the past couple of years without any problem. Recently, my network admin rebooted the server as a result of which I started getting LogonUser : Unknown user or bad password error. As per the network admin, everything is set up correctly for the domain user account. The username and password are all correct. Is there anything I need to change in the code below?
const int LOGON32_LOGON_INTERACTIVE = 2;
const int LOGON32_LOGON_NETWORK = 3;
const int LOGON32_LOGON_BATCH = 4;
const int LOGON32_LOGON_SERVICE = 5;
const int LOGON32_LOGON_UNLOCK = 7;
const int LOGON32_LOGON_NETWORK_CLEARTEXT = 8;
const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
const int LOGON32_PROVIDER_DEFAULT = 0;
[DllImport("advapi32.dll", SetLastError = true)]
public static extern int LogonUser(
string lpszUsername,
string lpszDomain,
string lpszPassword,
int dwLogonType,
int dwLogonProvider,
out IntPtr phToken
);
[DllImport("advapi32.dll", SetLastError = true)]
public static extern int ImpersonateLoggedOnUser(
IntPtr hToken
);
[DllImport("advapi32.dll", SetLastError = true)]
static extern int RevertToSelf();
[DllImport("kernel32.dll", SetLastError = true)]
static extern int CloseHandle(IntPtr hObject);
int TResult = LogonUser(ConfigurationManager.AppSettings["ServerUserName"].ToString(), @"\\server\folder", ConfigurationManager.AppSettings["ServerPassword"].ToString(), LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, out lnToken);
Please advise on what else I should be checking with my network admin. Thanks in advance.
I don’t see anything inherently wrong with the code that you are executing. So, I’m not certain why this would suddenly STOP working. However, if you are open to a little re-factoring there appear to be others that have run into similar issues. One of the below answers should give you the insight you need.
How to Impersonate a user for a file copy over the network when dns or netbios is not available
Accessing Password Protected Network Drives in Windows in C#?