In C# I would like test the availability of a network path, what authentication needed. I am using the following function:
private bool TestDrive(string path,string userName,string domain, string password)
{
if (userName == "")
return true;
//else authentication needed
try
{
using (new CImpersonator(userName, domain, password))
{
using (FileStream fs = File.Create(path+"\\1.txt"))
{ }
File.Delete(path + "\\1.txt");
}
return true;
}
catch (Exception ex)
{
return false;
}
}
public CImpersonator(
string userName,
string domainName,
string password,
bool checkUserName = true)
{
//Check if user exists
if (checkUserName && !CCheckUsername.UserExists(userName))
return;
this.ImpersonateValidUser(userName, domainName, password);
}
private void ImpersonateValidUser(
string userName,
string domain,
string password)
{
WindowsIdentity tempWindowsIdentity = null;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
try
{
if (RevertToSelf())
{
if (LogonUser(
userName,
domain,
password,
LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT,
ref token) != 0)
{
if (DuplicateToken(token, (int)System.Management.ImpersonationLevel.Impersonate, ref tokenDuplicate) != 0)
{
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
_impersonationContext = tempWindowsIdentity.Impersonate();
bool retVal;
TokPriv1Luid tp;
IntPtr hproc = (IntPtr)System.Diagnostics.Process.GetCurrentProcess().Id;
IntPtr htok = IntPtr.Zero;
retVal = OpenProcessToken(hproc, TOKEN_ALL_ACCESS, ref htok);
tp.Count = 1;
tp.Luid = 0;
tp.Attr = SE_PRIVILEGE_ENABLED;
retVal = LookupPrivilegeValue(null, SE_SYSTEMTIME_NAME, ref tp.Luid);
retVal = AdjustTokenPrivileges(token, false, ref tp, Marshal.SizeOf(typeof(TokPriv1Luid)), IntPtr.Zero, IntPtr.Zero);
}
else
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
else
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
else
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
finally
{
if (token != IntPtr.Zero)
{
CloseHandle(token);
}
if (tokenDuplicate != IntPtr.Zero)
{
CloseHandle(tokenDuplicate);
}
}
}
The problem is that when I use this for test a network path in an another domain, then the TestDrive
function returns false. Of course the domain, username and password are good, the user rights are good.
It is strange that the function works good, when I test it in the same domain.
Thank you for all ideas!