说我在闪亮的服务器上有一个共享:
\\server1\MyShare
如果我这样做:
Directory.Exists("\\server1\MyShare") //Returns True
现在我将电缆从服务器中拉出并再次运行代码:
Directory.Exists("\\server1\MyShare") //Returns False
我想知道它是否返回false,因为......:
实现这一目标的最简单方法是什么?
答案 0 :(得分:2)
检查您是否可以ping服务器
答案 1 :(得分:2)
Ping服务器:http://msdn.microsoft.com/en-us/library/system.net.networkinformation.ping.aspx
阻止示例:
Ping ping = new Ping();
PingResponse response = ping.PingHost(@"\\server1", 4);
答案 2 :(得分:2)
我遇到了类似的问题,但是因为我追求的目录是一个额外的层(\\Server\Share\Directory
),我能够用简单的方法作弊;
if( Directory.Exists("\\Server\Share") && !Directory.Exists("\\Server\Share\Directory") )
//Server is up, directory doesn't exist
..etc..
有潜在的时间/竞争条件,但它还没有给我带来任何问题。
答案 3 :(得分:1)
这些答案将有助于您提出问题的第一部分 - 如何检查远程服务器是否正在响应:C# Check Remote Server
至于部分b)你的Directory.Exists
方法是最好的方法 - 但是你可能想要使用WMI来检查文件夹,但是这比使用你已经拥有的东西要慢得多和麻烦。< / p>
答案 4 :(得分:1)
Ping有点笨拙,根据您的网络设置方式,可能不允许ping或其他设备可能响应ping。
此代码会根据您尝试访问的文件夹的状态将三条消息中的一条写入控制台:
try
{
DirectoryInfo diNoServer = new DirectoryInfo(@"\\non.existant.server\share");
diNoServer.Attributes = diNoServer.Attributes;
if (!diNoServer.Exists)
{
Console.WriteLine("The server was responsive, but the directory did not exist");
}
else
{
Console.WriteLine("all good");
}
}
catch (IOException exception)
{
Console.WriteLine("The server was unreachable");
}
答案 5 :(得分:0)
如果条件返回false,您可以让代码执行ping以查看服务器是否实际可用
答案 6 :(得分:0)
通常,如果共享不可访问,则说明出现问题,处理应停止。
如果由于某种原因(网络关闭、服务器关闭、禁止访问等)无法访问共享,我使用以下扩展程序抛出异常
public static class DirectoryExtension
{
public static bool IsShareAccessible(String unc)
{
if (Path.IsPathRooted(unc))
{
var share = Path.GetPathRoot(unc);
return Directory.Exists(share);
}
return true; //true is is not unc or full local path
}
}
使用方法:
if (!Directory.IsShareAccessible(@"\\server\share\folder"))
Throw new ApplicationException("can't access share");
if (!Directory.Exists(@"\\server\share\folder") {
...