VB.NET - WNetAddConnection2 - “找不到网络路径。”

VB.NET - WNetAddConnection2 - “找不到网络路径。”

问题描述:

我正在使用以下代码与网络路径建立连接以获取文件列表。VB.NET - WNetAddConnection2 - “找不到网络路径。”

网络路径非常正确,我可以使用相同的凭据手动映射驱动器。就在运行此代码时,显示错误:“53”,意思是“未找到网络路径”。

该错误突然发生,这表明即使连接没有被建立。

Dim nr As New NETRESOURCE 
    nr.dwType = RESOURCETYPE_DISK 
    nr.lpRemoteName = "\\fileserver.ourserver.com\" 
    MessageBox.Show(WNetAddConnection2(nr, "Password", "ourserver.com\User", 0)) 

的其他代码是:

Imports System.Runtime.InteropServices 
Imports System 
Imports System.IO 


Public Class Form1 


    <StructLayout(LayoutKind.Sequential)> _ 
    Private Structure NETRESOURCE 
     Public dwScope As UInteger 
     Public dwType As UInteger 
     Public dwDisplayType As UInteger 
     Public dwUsage As UInteger 
     <MarshalAs(UnmanagedType.LPTStr)> _ 
     Public lpLocalName As String 
     <MarshalAs(UnmanagedType.LPTStr)> _ 
     Public lpRemoteName As String 
     <MarshalAs(UnmanagedType.LPTStr)> _ 
     Public lpComment As String 
     <MarshalAs(UnmanagedType.LPTStr)> _ 
     Public lpProvider As String 
    End Structure 

    Private Const NO_ERROR As Long = 0 
    Private Const RESOURCETYPE_DISK As UInteger = 1 

    <DllImport("mpr.dll", CharSet:=CharSet.Auto)> _ 
    Private Shared Function WNetAddConnection2(ByRef lpNetResource As NETRESOURCE, <[In](), MarshalAs(UnmanagedType.LPTStr)> ByVal lpPassword As String, <[In](), MarshalAs(UnmanagedType.LPTStr)> ByVal lpUserName As String, ByVal dwFlags As UInteger) As UInteger 
    End Function 

    <DllImport("mpr.dll", CharSet:=CharSet.Auto)> _ 
    Private Shared Function WNetCancelConnection2(<[In](), MarshalAs(UnmanagedType.LPTStr)> ByVal lpName As String, ByVal dwFlags As UInteger, <MarshalAs(UnmanagedType.Bool)> ByVal fForce As Boolean) As UInteger 
    End Function 



End Class 
+0

StructLayout属性需要CharSet:= CharSet.Auto才能使其与函数声明相匹配。 –

不确定原因,但是现在让服务器路径添加/ IPC $让我再次使用它。

是否有您使用的互操作类,列出你的文件有原因的,你可以使用.NET Framework来DiriectoryInfo类来这样做。

+0

旧代码,之前使用不同的方法,但现在使用DirectoryInfo。 – MRC