I am trying to see if a directory exists based on an input field from the user. When the user types in the path, I want to check if the path actually exists.
I have some c# code already. It returns 1 for any local path, but always returns 0 when I am checking a network path.
static string checkValidPath(string path)
{
//Insert your code that runs under the security context of the authenticating user here.
using (ImpersonateUser user = new ImpersonateUser(user, "", password))
{
//DirectoryInfo d = new DirectoryInfo(quotelessPath);
bool doesExist = Directory.Exists(path);
//if (d.Exists)
if(doesExist)
{
user.Dispose();
return "1";
}
else
{
user.Dispose();
return "0";
}
}
}
public class ImpersonateUser : IDisposable
{
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);
[DllImport("kernel32", SetLastError = true)]
private static extern bool CloseHandle(IntPtr hObject);
private IntPtr userHandle = IntPtr.Zero;
private WindowsImpersonationContext impersonationContext;
public ImpersonateUser(string user, string domain, string password)
{
if (!string.IsNullOrEmpty(user))
{
// Call LogonUser to get a token for the user
bool loggedOn = LogonUser(user, domain, password,
9 /*(int)LogonType.LOGON32_LOGON_NEW_CREDENTIALS*/,
3 /*(int)LogonProvider.LOGON32_PROVIDER_WINNT50*/,
out userHandle);
if (!loggedOn)
throw new Win32Exception(Marshal.GetLastWin32Error());
// Begin impersonating the user
impersonationContext = WindowsIdentity.Impersonate(userHandle);
}
}
public void Dispose()
{
if (userHandle != IntPtr.Zero)
CloseHandle(userHandle);
if (impersonationContext != null)
impersonationContext.Undo();
}
}
Any help is appreciated. Thanks!
EDIT 3: updated code to use BrokenGlass's impersonation functions. However, I need to initialize "password" to something...
EDIT 2: I updated the code to try and use impersonation as suggested below. It still fails everytime. I assume I am using impersonation improperly...
EDIT: As requested by ChrisF, here is the function that calls the checkValidPath function.
Frontend aspx file...
$.get('processor.ashx', { a: '7', path: x }, function(o) {
alert(o);
if (o=="0") {
$("#outputPathDivValid").dialog({
title: 'Output Path is not valid! Please enter a path that exists!',
width: 500,
modal: true,
resizable: false,
buttons: {
'Close': function() { $(this).dialog('close'); }
}
});
}
});
Backend ashx file...
public void ProcessRequest (HttpContext context) {
context.Response.Cache.SetExpires(DateTime.Now);
string sSid = context.Request["sid"];
switch (context.Request["a"])
{//a bunch of case statements here...
case "7":
context.Response.Write(checkValidPath(context.Request["path"].ToString()));
break;