[英]Using Directory.Exists on a network folder when the network is down
我公司的代码库包含以下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分钟的网络超时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.