2009-10-01 如何動態連線/斷線UNC路徑(不建立網路磁碟機) 14391 0 VB.Net / C#.Net / 摘要:如何動態連線/斷線UNC路徑(不建立網路磁碟機) 如何動態連線 / 斷線UNC路徑 (不建立網路磁碟機)UNC ( Universal Naming Conversion )Imports System Public Class Form1 ' 結構 Private Structure NetResrc Dim dwScope As Int32 Dim dwType As Int32 Dim dwDisplayType As Int32 Dim dwUsage As Int32 Dim lpLocalName As String Dim lpRemoteName As String Dim lpComment As String Dim lpProvider As String End Structure ' API 宣告 Private Declare Function WNetAddConnection2A Lib "mpr.dll" _ (ByVal lpNetResource As NetResrc, _ ByVal lpPswd As String, ByVal lpUser As String, _ ByVal dwFlags As Int32) As Int32 Private Declare Function WNetCancelConnection2A Lib "mpr.dll" _ (ByVal lpName As String, _ ByVal dwFlags As Int32, _ ByVal fForce As Int32) As Int32 Private Sub btnConnect_Click(ByVal s As Object, ByVal e As EventArgs) Handles btnConnect.Click Dim UNC As String = "\\192.168.10.XX\ShareFolder" ' UNC Path Dim User As String = "LoginUser" ' Login User Dim Pswd As String = "LoginPassword" ' Password If ConnectUNC(UNC, User, Pswd) Then MessageBox.Show("UNC 連線成功 OK !") End Sub Private Sub btnDisconnect_Click(ByVal s As Object, ByVal e As EventArgs) Handles btnDisconnect.Click Dim UNC As String = "\\192.168.10.XX\ShareFolder" ' UNC Path If DisconnectUNC(UNC) Then MessageBox.Show("UNC 斷線成功 !") End Sub ' UNC連線 Private Shared Function ConnectUNC _ (ByVal Unc As String, ByVal User As String, ByVal Pwd As String) As Boolean Dim NetStruc As New NetResrc If Unc.EndsWith("\") Then Unc = Unc.Substring(0, Unc.Length - 1) NetStruc.dwType = 0 NetStruc.lpLocalName = "" NetStruc.lpRemoteName = Unc NetStruc.lpProvider = "" ConnectUNC = WNetAddConnection2A(NetStruc, Pwd, User, 0) = 0 End Function ' UNC斷線 Private Shared Function DisconnectUNC(ByVal Unc As String) As Boolean If Unc.EndsWith("\") Then Unc = Unc.Substring(0, Unc.Length - 1) DisconnectUNC = WNetCancelConnection2A(Unc, 1, 0) = 0 ' 如果需要要斷 \\Server\IPC$ 如下 'Dim ipc As String = String.Format("\\{0}\IPC$", UNC.Split("\")(2)) 'WNetCancelConnection2A(ipc, 1, 1) End Function End Class UNC.Net 回首頁