检查C#中服务器路径是否可用作文件共享

3
我希望能够快速检查C#中的文件共享是否可用,但却不知道可能在网络共享上的目录。我已经找到了这些文章 1 2 3,它们展示了如何检查网络目录是否可用,但都假定我知道要检查是否存在的目录共享。也就是说,它们要检查\\SomeServer\SomeDirectory是否可用,但我只想检查\\SomeServer是否可用。
稍微详细解释一下我正在尝试做什么,我提示用户连接到一个SQL服务器,并给出一个地址,例如“SQL001”。显然,此地址只在我们内部的网络上有效。使用此地址,我可以连接到服务器及其数据库。现在,我给他们提供备份数据库的选项,并希望OpenFileDialog将InitialDirectory设置为"\\SQL001",以便他们可以快速访问该服务器上的共享文件夹并在远程服务器上备份数据库。
如果我将"\\SQL001"设置为OpenFileDialog的InitialDirectory,一切都很顺利,但是如果他们打错了并输入了"\\SQL002"(不存在),或者可能在内部网络外使用该工具,则OpenFileDialog的ShowDialog函数会抛出错误。因此,我想先检查并确保文件共享可用,如果不可用则不设置InitialDirectory。
使用Directory.Exists("\\SQL001")总是返回false。不幸的是。如果我做Directory.Exists("\\SQL001\Backups"),它会起作用,但我们有许多不同的SQL服务器,它们并没有叫做“Backups”的共享,因此这是不可靠的。我还可以使用Directory.Exists("\\SQL001\c$\"),这对我有效,但许多员工将无权访问根C:\,但将拥有访问网络共享的权限,因此这也不是一个好的替代方案。
因此,我的问题是,假设用户拥有文件共享的权限,如何检查文件共享是否可用?同时,我也不想强制用户将“\\SQL001”映射为网络驱动器
现在我唯一看到的解决方案就是只调用OpenFileDialog的ShowDialog函数并捕获特定的异常,清除InitialDirectory,然后再次调用ShowDialog。这将起作用,但感觉有点笨拙,因此我希望能有更好的解决方案。
3个回答

7

你能告诉我如何检查本地PC上的共享文件夹是否存在吗?我需要从口袋PC(使用.NET Compact Framework)进行测试。 - user2681579

2

根据Allan Elder的回答,我提出了以下解决方案,似乎可以工作。我使用了 System.Net.Dns.GetHostEntry() 而不是GetHostByName,因为GetHostByName现在已经被弃用了。

/// <summary>
/// Gets the rooted path to use to access the host.
/// Returns an empty string if the server is unavailable.
/// </summary>
/// <param name="serverName">The server to connect to.</param>
public static string GetNetworkPathFromServerName(string serverName)
{
    // Assume we can't connect to the server to start with.
    var networkPath = String.Empty;

    // If this is a rooted path, just make sure it is available.
    if (Path.IsPathRooted(serverName))
    {
        // If the path exists, use it.
        if (Directory.Exists(serverName))
            networkPath = serverName;
    }
        // Else this is a network path.
    else
    {
        // If the server name has a backslash in it, remove the backslash and everything after it.
        serverName = serverName.Trim(@"\".ToCharArray());
        if (serverName.Contains(@"\"))
            serverName = serverName.Remove(serverName.IndexOf(@"\", StringComparison.Ordinal));

        try
        {
            // If the server is available, format the network path properly to use it.
            if (Dns.GetHostEntry(serverName) != null)
            {
                // Root the path as a network path (i.e. add \\ to the front of it).
                networkPath = String.Format("\\\\{0}", serverName);
            }
        }
        // Eat any Host Not Found exceptions for if we can't connect to the server.
        catch (System.Net.Sockets.SocketException)
        { }
    }

    return networkPath;
}

你能告诉我如何检查本地PC上的共享文件夹是否存在吗?我需要从口袋PC(使用.NET Compact Framework)进行测试,请参考此链接:https://stackoverflow.com/questions/25710537/check-shared-path-is-available-in-pc - user2681579

0
如果您打算在检查服务器可用性后使用Windows文件共享,则有效的方法是打开到NetBIOS端口(139)的套接字,该端口用于文件共享服务。这不仅会告诉您服务器是否在线,还会告诉您它是否可用于文件操作。完整的.NET源代码在此处。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接