检查网络上是否存在目录c#

Mr.*_*Ant 1 c# jquery

我试图根据用户的输入字段查看目录是否存在.当用户键入路径时,我想检查路径是否确实存在.

我已经有了一些C#代码.对于字符串"C:\ Program Files",它总是返回0,EXCEPT ...

static string checkValidPath(string path)
{
    //Insert your code that runs under the security context of the authenticating user here.
    using (ImpersonateUser user = new ImpersonateUser("myusername", "", "mypassword"))
    {
        //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();
    }
}
Run Code Online (Sandbox Code Playgroud)

任何帮助表示赞赏.谢谢!

编辑4:终于找到了解决方案!见下面的答案.BrokenGlass的代码也会起作用.我发现添加web.config文件更快.

编辑3:更新代码以使用BrokenGlass的模拟函数.仍然没有运气......

编辑2:我更新了代码,尝试使用模仿,如下所示.它每次都失败了.我假设我不正当地使用假冒......

编辑:根据ChrisF的要求,这是调用checkValidPath函数的函数.

前端aspx文件...

$.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'); }
                    }
                });
            }
        });
Run Code Online (Sandbox Code Playgroud)

后端ashx文件...

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;
Run Code Online (Sandbox Code Playgroud)

Chr*_*isF 6

从MSDN页面的Exists属性:

如果在尝试确定指定文件是否存在时发生任何错误,则Exists属性返回false.在引发异常的情况下会发生这种情况,例如传递带有无效字符或字符太多的文件名,磁盘失败或丢失,或者调用者没有读取文件的权限.

因此,请执行以下任何一项操作:

  1. 路径是否包含任何无效字符?
  2. 太长了吗?
  3. 它实际上是否描述了存在的路径?
  4. 进程的所有者是否有权读取文件?

第4点很重要.虽然"你"作为开发人员在本地测试应用程序时可能拥有权限,但您需要确保在服务器上运行该程序的帐户具有权限.如果不是,应用程序将失败,当您尝试重复该问题时,它将不会显而易见.


Bro*_*ass 5

尝试

 bool doesExist = Directory.Exists(path);
Run Code Online (Sandbox Code Playgroud)

您的代码也适用于我,请确保您传递完整路径,即@"C:\myDir\myDir2"代替"myDir2"

要模拟用户的网络路径,请尝试以下操作:

using(ImpersonateUser user = new ImpersonateUser(user, "", password))
{
     bool doesExist = Directory.Exists(networkPath);
}
Run Code Online (Sandbox Code Playgroud)

这基于以下帮助程序类:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)