C#Directory.exist始终在本地网络上返回false

时间:2013-04-05 09:30:39

标签: c# networking directory impersonation

我正在尝试检查目录是否存在于本地网络上。在对stackoverflow和MSDN进行一些研究之后,我使用模拟方法开发了我的代码。问题是效果不好,Directory.exists()方法始终返回False这里有我的代码(它与MSDN中的代码几乎相同):

public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
    {
        private SafeTokenHandle()
            : base(true)
        {
        }

        [DllImport("kernel32.dll")]
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        [SuppressUnmanagedCodeSecurity]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool CloseHandle(IntPtr handle);

        protected override bool ReleaseHandle()
        {
            return CloseHandle(handle);
        }
    }

 class Environment
    {
        [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
            int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public extern static bool CloseHandle(IntPtr handle);
        const int LOGON32_PROVIDER_DEFAULT = 0;
        const int LOGON32_LOGON_INTERACTIVE = 2;

        private void m_SendAlertes()
        {
                SafeTokenHandle safeTokenHandle;
                string v_pathToDir = "\\192.168.1.199\Clients SiteInternet";

                if (!LogonUser("RKalculateur", "SERVEUR2", 
                                "riskedge", LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out safeTokenHandle))
                {
                    int ret = Marshal.GetLastWin32Error();
                    throw new System.ComponentModel.Win32Exception(ret);
                }
                using (safeTokenHandle)
                {
                    using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))
                    {
                        using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
                        {
                            if (Directory.Exists(@v_pathToDir))
                            {
                               // Proceed code here
                            }
                        }
                    }
                }
        }
    }

您可以在此处获得此目录的权限: enter image description here

1 个答案:

答案 0 :(得分:4)

这可能是与用户权限相关的问题。

来自MSDN:

  

如果您没有至少的只读权限   目录,Exists方法将返回false。

如果您使用的是本地帐户而非域帐户,则使用Directory.Exists()方法会出现问题。

我过去遇到过类似的问题:我必须检查网络中是否存在网络共享,并且没有域名。你的方式对我不起作用。最后,我放弃了Directory.Exists()方法并最终使用了NET USE命令(http://www.cezeo.com/tips-and-tricks/net-use-command/

bool exists = false;
string output = "";
string error = "";

System.Diagnostics.Process process = new System.Diagnostics.Process();
process = new System.Diagnostics.Process();
            ExecuteShellCommand(process, "NET USE", "\""+ @path + "\" "+
               this.password+ " /USER:"+machinename+"\\"+username + " /PERSISTENT:NO",
               ref output, ref error);
Console.WriteLine("\r\n\t__________________________"+
                "\r\n\tOutput:" + output.Trim().Replace("\r", " ") +
                "\r\n\tError: " + error.Trim().Replace("\r"," "));

            if (output.Length>0 && error.Length==0)
            {
                exists = true;
            }

            process = new System.Diagnostics.Process();
            ExecuteShellCommand(process, "NET USE", " /DELETE " + @path,
                ref output, ref error);

...

public void ExecuteShellCommand(System.Diagnostics.Process process, string fileToExecute,
        string command, ref string output, ref string error)
    {
        try
        {
            string CMD = string.Format(System.Globalization.CultureInfo.InvariantCulture, @"{0}\cmd.exe", new object[] { Environment.SystemDirectory });
            string args = string.Format(System.Globalization.CultureInfo.InvariantCulture, "/C {0}", new object[] { fileToExecute });
            if (command != null && command.Length > 0)
            {
                args += string.Format(System.Globalization.CultureInfo.InvariantCulture, " {0}", new object[] { command, System.Globalization.CultureInfo.InvariantCulture });
            }

            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(CMD, args);

            startInfo.CreateNoWindow = true;
            startInfo.UseShellExecute = false;
            startInfo.RedirectStandardOutput = true;
            startInfo.RedirectStandardInput = true;
            startInfo.RedirectStandardError = true;

            process.StartInfo = startInfo;

            process.Start();

            // timeout
process.WaitForExit(10 * 1000);
output = process.StandardOutput.ReadToEnd();
             error = process.StandardError.ReadToEnd();
        }
        catch (Win32Exception e32)
        {
            Console.WriteLine("Win32 Exception caught in process: {0}", e32.ToString());
        }
        catch (Exception e
        {
            Console.WriteLine("Exception caught in process: {0}", e.ToString());
        }
        finally
        {
            // close process and do cleanup
            process.Close();
            process.Dispose();
            process = null;
        }
    }

我知道这是一个黑客但它对我有用,这是一种可能性。 (尽管您可能需要设置适当的净份额)