我們的ASP.NET項目使用單獨的文件服務器上。我們發現一個可靠的方法是通過WNetAddConnection2A
API調用打開輔助連接。這是一個基本的實現(VB.NET)
API聲明
<StructLayout(LayoutKind.Sequential)> Private Structure NETRESOURCE
Public dwScope As Integer
Public dwType As Integer
Public dwDisplayType As Integer
Public dwUsage As Integer
<MarshalAs(UnmanagedType.LPStr)> Public lpLocalName As String
<MarshalAs(UnmanagedType.LPStr)> Public lpRemoteName As String
<MarshalAs(UnmanagedType.LPStr)> Public lpComment As String
<MarshalAs(UnmanagedType.LPStr)> Public lpProvider As String
End Structure
<DllImport("mpr.dll")> _
Private Shared Function WNetAddConnection2A(_
<MarshalAs(UnmanagedType.LPArray)> ByVal lpNetResource As NETRESOURCE(), _
<MarshalAs(UnmanagedType.LPStr)> ByVal lpPassword As String, _
<MarshalAs(UnmanagedType.LPStr)> ByVal lpUserName As String, _
ByVal dwFlags As Integer) As Integer
End Function
<DllImport("mpr.dll")> _
Private Shared Function WNetCancelConnection2A(_
<MarshalAs(UnmanagedType.LPStr)> ByVal lpName As String, _
ByVal dwFlags As Integer, ByVal fForce As Integer) As Integer
End Function
Public Shared Sub WNetAddConnection2AEx(ByVal i_sPath As String, ByVal i_sPassword As String, ByVal i_sUserID As String)
Dim nr(1) As NETRESOURCE
nr(0).lpRemoteName = i_sPath
nr(0).lpLocalName = ""
nr(0).dwType = 1
nr(0).dwDisplayType = 0
nr(0).dwScope = 0
nr(0).dwUsage = 0
nr(0).lpComment = ""
nr(0).lpProvider = ""
Dim iErr As Integer = WNetAddConnection2A(nr, i_sPassword, i_sUserID, 0)
If iErr > 0 Then Throw New Exception("Can not connect to share folder: " & i_sPath)
End Sub
使用
WNetAddConnection2AEx("\\server\path", "password", "user_id")
''...
''perform your file operation here
''...
WNetCancelConnection2A("\\server\path", 0, -1)
您是否嘗試過直接寫入文件而不通過應用程序?同時獲取失敗操作的進程監視器輸出可能會有所幫助 – Mike
直接編寫文件可以起作用。 –