Using Directory.Exists on a network folder when the network is down

后端 未结 2 731
误落风尘
误落风尘 2021-02-07 12:26

My company\'s code base contains the following C# line:

bool pathExists = Directory.Exists(path);

At runtime, the string path happ

2条回答
  •  别跟我提以往
    2021-02-07 13:18

    If general network connectivity is your primary problem, you could try testing the network connectivity prior to this:

        [DllImport("WININET", CharSet = CharSet.Auto)]
        static extern bool InternetGetConnectedState(ref int lpdwFlags, int dwReserved);
    
        public static bool Connected
        {
            get
            {
                int flags = 0;
                return InternetGetConnectedState(ref flags, 0);
            }
        }
    

    Then determine if the path is a UNC path and return false if the network is offline:

        public static bool FolderExists(string directory)
        {
            if (new Uri(directory, UriKind.Absolute).IsUnc && !Connected)
                return false;
            return System.IO.Directory.Exists(directory);
        }
    

    None of this helps when the host you're trying to connect to is offline. In that case you're still in for 2-minute network timeout.

提交回复
热议问题