VB.NET中如何检查网络驱动器是否已映射?
问题分析
你用WebClient的方法行不通,因为WebClient是针对HTTP/HTTPS这类Web协议设计的,而UNC路径(\\xxx格式)用的是SMB文件共享协议,两者不兼容,所以无法识别目标路径。Ping失效则大概率是目标服务器禁用了ICMP请求,或是防火墙拦截了ping包。
下面是几种可行的解决方案:
方案1:检查指定盘符是否映射到目标UNC路径
如果你的需求是确认某个盘符(比如Z:\)是否映射到目标共享路径,可以通过Windows API获取盘符对应的UNC地址,再做匹配:
Imports System.Runtime.InteropServices Imports System.IO Public Class NetworkDriveHelper ' 调用Windows API获取映射盘符对应的UNC路径 <DllImport("mpr.dll", CharSet:=CharSet.Unicode, SetLastError:=True)> Private Shared Function WNetGetConnection( ByVal localName As String, ByVal remoteName As StringBuilder, ByRef length As Integer ) As Integer End Function ' 根据盘符获取对应的UNC路径 Public Shared Function GetUncFromDrive(driveLetter As String) As String ' 统一盘符格式为 "X:\" If Not driveLetter.EndsWith(":\") Then driveLetter = $"{driveLetter}:\" End If Dim sb As New StringBuilder(512) Dim bufferLength As Integer = sb.Capacity Dim apiResult As Integer = WNetGetConnection(driveLetter, sb, bufferLength) ' API返回0表示成功获取 Return If(apiResult = 0, sb.ToString(), String.Empty) End Function ' 检查指定盘符是否映射到目标UNC Public Shared Function IsDriveMappedToTarget(driveLetter As String, targetUnc As String) As Boolean Dim mappedUnc As String = GetUncFromDrive(driveLetter) Return String.Equals(mappedUnc, targetUnc, StringComparison.OrdinalIgnoreCase) End Function End Class
使用示例:
' 检查Z盘是否映射到\\mynetowrk_Driver.com\system\application Dim isMapped As Boolean = NetworkDriveHelper.IsDriveMappedToTarget("Z", "\\mynetowrk_Driver.com\system\application") Console.WriteLine(isMapped)
方案2:直接验证UNC路径的可访问性
如果不需要检查盘符映射,只是确认目标共享路径是否能正常访问,可直接用Directory.Exists(针对目录)或File.Exists(针对文件),同时处理权限、网络异常:
Imports System.IO Public Function IsUncPathAccessible(targetUnc As String) As Boolean Try ' 验证目录是否存在 Return Directory.Exists(targetUnc) ' 如果是验证具体文件,替换为: ' Return File.Exists(Path.Combine(targetUnc, "你的应用文件名.exe")) Catch ex As Exception ' 捕获权限不足、网络中断等异常 Return False End Try End Function
使用示例:
Dim isAccessible As Boolean = IsUncPathAccessible("\\mynetowrk_Driver.com\system\application") Console.WriteLine(isAccessible)
方案3:遍历所有已映射的网络驱动器
如果要确认目标UNC是否被映射为任意盘符,可以遍历系统中所有网络驱动器并检查:
Imports System.IO Public Function IsUncMappedAsAnyDrive(targetUnc As String) As Boolean For Each drive As DriveInfo In DriveInfo.GetDrives() If drive.DriveType = DriveType.Network Then Dim mappedUnc As String = NetworkDriveHelper.GetUncFromDrive(drive.Name.TrimEnd("\"c)) If String.Equals(mappedUnc, targetUnc, StringComparison.OrdinalIgnoreCase) Then Return True End If End If Next Return False End Function
使用示例:
Dim isMapped As Boolean = IsUncMappedAsAnyDrive("\\mynetowrk_Driver.com\system\application") Console.WriteLine(isMapped)
注意事项
Directory.Exists需要当前程序拥有访问目标UNC路径的权限,否则会返回False- WNetGetConnection只能获取当前用户会话下的映射驱动器
- 如果目标服务器禁用了文件共享、网络不通,上述方法都会返回False
内容的提问来源于stack exchange,提问作者NBB
相关产品推荐
相关产品推荐

