【发布时间】:2014-01-10 20:54:34
【问题描述】:
我正在使用以下代码与网络路径建立连接以获取文件列表。
网络路径绝对正确,我可以使用相同的凭据手动映射驱动器。刚运行这段代码时,显示错误:“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
【问题讨论】:
-
StructLayout 属性需要 CharSet:=CharSet.Auto 以使其与函数声明匹配。