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

时间:2011-01-03 22:14:24

标签: 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();
    }
}

感谢任何帮助。谢谢!

编辑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'); }
                    }
                });
            }
        });

后端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;

5 个答案:

答案 0 :(得分:6)

来自Exists属性的MSDN page

  

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

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

  1. 路径是否包含任何无效字符?
  2. 太长了吗?
  3. 它是否实际描述了存在的路径?
  4. 进程所有者是否有权读取文件?
  5. 第4点很重要。虽然“你”作为开发人员在本地测试应用程序时可能拥有权限,但您需要确保在服务器上运行该程序的帐户具有权限。如果没有,应用程序将失败,当您尝试重复该问题时,它将不会显而易见。

答案 1 :(得分:5)

 bool doesExist = Directory.Exists(path);

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

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

using(ImpersonateUser user = new ImpersonateUser(user, "", password))
{
     bool doesExist = Directory.Exists(networkPath);
}

这基于以下帮助程序类:

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();
    }
}

答案 2 :(得分:1)

返回False,因为属性'Exists'表示目录是否存在 - 因此,如果将文件路径作为参数传递给DirectoryInfo构造函数,则返回false。如果您创建一个DirectoryInfo并将现有目录作为参数传递,那么您将获得真实。 如果要确定文件是否存在,则应使用以下命令进行检查:File.Exists 那么,您确定用户输入的path指向现有目录(而不是文件)吗?

答案 3 :(得分:0)

所有信息都在这里:http://msdn.microsoft.com/en-us/library/system.io.directory.exists.aspx

示例:

Directory.Exists(myPath);

答案 4 :(得分:0)

所以我找到了解决方案。我只是将web.config文件中的模拟添加到Web应用程序所在的文件夹中。这是我在文件中使用的代码......

<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
    <identity impersonate="true" userName="registry:HKLM\Software\medc\sys_content_pub,userName" password="registry:HKLM\Software\medc\sys_content_pub,password"/>
</system.web>

我可能忽略了这是一个网络应用程序。 :O然而,对于他所有的贡献,他们会向BrokenGlass大喊大叫。如果我研究了一种评估注册表值的方法,那么你的代码就可以了。

这是最终的checkValidPath函数......

static bool checkValidPath(string path)
{

    string quotelessPath = path.Replace("\"","");

    bool doesExist = Directory.Exists(quotelessPath);

    if(doesExist)
    {
        return true;
    }
    else
    {
        return false;
    }
}
相关问题