使用目录.当网络断开时,存在于网络文件夹中

本文关键字:网络 于网络 文件夹 存在 断开 | 更新日期: 2023-09-27 18:17:28

我公司的代码库包含以下c#行:

bool pathExists = Directory.Exists(path);

在运行时,字符串path恰好是公司内部网中某个文件夹的地址——比如''company'companyFolder。当我的Windows机器连接到内部网时,这工作得很好。但是,当连接断开时(就像今天一样),执行上面的代码会导致应用程序完全冻结。我只能通过任务管理器杀死应用程序来关闭它。

当然,在这种情况下,我宁愿Directory.Exists(path)返回false。有办法做到这一点吗?

使用目录.当网络断开时,存在于网络文件夹中

在这种情况下没有办法改变Directory.Exists的行为。在底层,它通过网络在UI线程上发出同步请求。如果网络连接由于中断、流量过大等原因而挂起……它也会导致UI线程挂起。

你能做的最好的是在后台线程发出这个请求,并在一定的时间后明确地放弃。例如

Func<bool> func = () => Directory.Exists(path);
Task<bool> task = new Task<bool>(func);
task.Start();
if (task.Wait(100)) {
  return task.Value;
} else {
  // Didn't get an answer back in time be pessimistic and assume it didn't exist
  return false;
}

如果一般网络连接是您的主要问题,您可以在此之前尝试测试网络连接:

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

然后判断该路径是否是UNC路径,如果网络离线则返回false:

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

当您试图连接的主机离线时,这些都没有帮助。在这种情况下,您仍然处于2分钟的网络超时。