How to (quickly) check if UNC Path is available

前端 未结 7 657
太阳男子
太阳男子 2020-12-05 06:45

How can I check if a UNC Path is available? I have the problem that the check takes about half a minute if the share is not available :

var          


        
7条回答
  •  心在旅途
    2020-12-05 07:02

    I used the ping method suggested above and it did not work for me since I am using OpenDNS Here is a function that worked well for me:

    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    /// 
    /// A quick method to test is the path exists 
    /// 
    /// 
    /// 
    /// 
    public static bool CheckPathExists(string s, int timeOutMs = 120) {
        if (s.StartsWith(@"\\")) {
            Uri uri = new Uri(s);
            if (uri.Segments.Length == 0 || string.IsNullOrWhiteSpace(uri.Host))
                return false;
            if (uri.Host != Dns.GetHostName()) {
                WebRequest request;
                WebResponse response;
                request = WebRequest.Create(uri);
                request.Method = "HEAD";
                request.Timeout = timeOutMs;
                try {
                    response = request.GetResponse();
                } catch (Exception ex) {
                    return false;
                }
                return response.ContentLength > 0;
    
                // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
                // Do a Ping to see if the server is there
                // This method doesn't work well using OPenDNS since it always succeeds
                // regardless if the IP is a valid or not
                // OpenDns always maps every host to an IP. If the host is not valid the 
                // OpenDNS will map it to 67.215.65.132
                /* Example:
                    C:\>ping xxx
    
                    Pinging xxx.RT-AC66R [67.215.65.132] with 32 bytes of data:
                    Reply from 67.215.65.132: bytes=32 time=24ms TTL=55
                    */
    
                //Ping pingSender = new Ping();
                //PingOptions options = new PingOptions();
                // Use the default Ttl value which is 128,
                // but change the fragmentation behavior.
                //options.DontFragment = true;
    
                // Create a buffer of 32 bytes of data to be transmitted.
                //string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
                //byte[] buffer = Encoding.ASCII.GetBytes(data);
                //int timeout = 120;
                //PingReply reply = pingSender.Send(uri.Host, timeout, buffer, options);
                //if (reply == null || reply.Status != IPStatus.Success)
                //    return false;
            }
        }
        return File.Exists(s);
    }
    

提交回复
热议问题