Hi @Mansour_Dalir ,
You could consider using the WNetAddConnection2 function from the Windows API to map the network drive with the provided credentials before accessing the file.
<StructLayout(LayoutKind.Sequential)>
Public Structure NETRESOURCE
Public dwScope As Integer
Public dwType As Integer
Public dwDisplayType As Integer
Public dwUsage As Integer
<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
<DllImport("mpr.dll", CharSet:=CharSet.Auto)>
Public Shared Function WNetAddConnection2(ByRef netResource As NETRESOURCE, ByVal password As String, ByVal username As String, ByVal flags As Integer) As Integer
End Function
<DllImport("mpr.dll", CharSet:=CharSet.Auto)>
Public Shared Function WNetCancelConnection2(ByVal lpName As String, ByVal dwFlags As Integer, ByVal fForce As Boolean) As Integer
End Function
Private Sub MapNetworkDrive()
Dim nr As New NETRESOURCE()
nr.dwType = 1 ' RESOURCETYPE_DISK
nr.lpRemoteName = "\\192.168.80.111\mansour"
Dim result As Integer = WNetAddConnection2(nr, "00137300", "Almas", 0)
If result <> 0 Then
Throw New System.ComponentModel.Win32Exception(result)
End If
End Sub
Private Sub DisconnectNetworkDrive()
Dim result As Integer = WNetCancelConnection2("\\192.168.80.111\mansour", 0, True)
If result <> 0 Then
Throw New System.ComponentModel.Win32Exception(result)
End If
End Sub
Private Sub WriteToFile()
Try
MapNetworkDrive()
Dim filePath As String = "\\192.168.80.111\mansour\asd.txt"
Dim textToWrite As String = "Hello, World!"
System.IO.File.WriteAllText(filePath, textToWrite)
Catch ex As Exception
Console.WriteLine("Error: " & ex.Message)
Finally
DisconnectNetworkDrive()
End Try
End Sub
Best Regards.
Jiachen Li
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.