c# - 如何 ping 映射驱动器

标签 c#

您好,我正在编写一个应用程序,用户可以在其中输入用于存储某些文件的目录。

如果他输入了运行程序的机器上的目录,我可以使用他输入的路径。

万一他进入网络上的目录是这样的:192.168.xxx.xxx..., 我可以 ping 通,如果可以 ping 通则使用此路径。

但是如果用户有映射驱动器并输入类似 Y:\work... 的内容怎么办? .Net Ping 类有一个 Send 方法,我这样使用它:

try{
    Ping pinger = new Ping();
    PingReply reply = pinger.Send(NetworkIP);
} catch (PingException) {
    // Discard PingExceptions and return false;
}

但是,如果 NetworkIP 是 Y:\或其他内容,即使驱动器应该可用,它也会抛出 PingException。

有人知道我该如何解决这个问题吗?也许我可以以某种方式获取驱动器的 IP 地址并使用它?

感谢您的帮助

最佳答案

您可以检查该网络驱动器是否准备就绪。
有一个DriveInfo .NET Framework 中的类,指示驱动器是否准备就绪(如果 CD 插入 CD ROM 设备中,或者可移动存储是否已准备好进行 IO,这也适用于网络驱动器)。

我已经使用一个小型 PowerShell 脚本快速测试了这一点以验证这一点,这是我的输出:

Name               : Y:\
DriveType          : Network
DriveFormat        : 
IsReady            : False
AvailableFreeSpace : 
TotalFreeSpace     : 
TotalSize          : 
RootDirectory      : Y:\
VolumeLabel        : 

Name               : Z:\
DriveType          : Network
DriveFormat        : HGFS
IsReady            : True
AvailableFreeSpace : 420309352448
TotalFreeSpace     : 420309352448
TotalSize          : 500105736192
RootDirectory      : Z:\
VolumeLabel        : Shared Folders

您可以使用 MSDN 文档中给出的示例为您的应用程序编写代码,如下所示(尚未测试,但应该可以工作):

using System;
using System.IO;

class MyClass {
    public bool CheckNetworkDrive(String name) {
        bool result = false;
        DriveInfo[] drives = DriveInfo.GetDrives();
        foreach (DriveInfo d in drives) {
            if (d.Name == name) {
                result = d.IsReady;
            }
        }
        return result;
    }
}

关于c# - 如何 ping 映射驱动器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31176849/

相关文章:

c# - VSTO - Outlook 添加上下文菜单

c# - 如何将字符串分成数组

c# - 使用 Microsoft DI 在泛型构造函数中注入(inject)基本类型

c# - 使用 MSIEnumRelatedProducts 和 MSIGetProductInfo 的 MSI Interop

javascript - 向 Web API 发送参数时参数值设置为 0

c# - SQL Server 连接计数问题

c# - 检查对象是否已存在于集合中

javascript - 将项目列表从 $.get() 传递到 MVC Controller

c# - GridViewColumn.Width 绑定(bind)并双击以自动调整列大小

c# - PInvokeStackImbalance 不是由 CallingConvention 引起的