3

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

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
                            }
                        }
                    }
                }
        }
    }

在这里,您可以看到此目录的权限图片: 在此处输入图像描述

4

1 回答 1

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

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

于 2013-04-05T11:08:30.907 回答