Map network remotely in Asp.net VB

Hi I am using asp.net with vb, I want functionality so I can first my remote drive mapped first then access file and then unmap that drive, How I can do that in asp.net?
SudhanshumAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Pallavi GodseSr. Digital Marketing ExecutiveCommented:
You need to map drive letters to a network drive and this is valid only for the account for which you have done this. So when your ASP.NET code runs on a web server it will use a particular account and you would need to configure the drive letter you want for this account.
0
SudhanshumAuthor Commented:
Can u provide syntax for that? It should need userName,password also.
0
SudhanshumAuthor Commented:
I need immediate help.
0
Scott McDaniel (Microsoft Access MVP - EE MVE )Infotrakker SoftwareCommented:
If you need immediate, on-demand help you might considering using the Live or Gigs platform to have experts at your beck and call. Otherwise, please understand we're all Volunteer, and we assist when our real lives allow it.
0
it_saigeDeveloperCommented:
Mapping a network drive and disconnecting are really very simple, it's as Scott states, you just need to ensure that your App Identity User or Authenticated User (whichever run's the associated call) has access to the remote system and share.

So to control the drive mapping and disconnecting the mapped drive; you can use something like this:
Imports System.IO
Imports System.Net
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Imports System.Text.RegularExpressions

Class NetworkConnection
	Implements IDisposable

	ReadOnly _credentials As NetworkCredential = Nothing
	ReadOnly _driveLetter As String
	ReadOnly _networkResource As NetworkResource = New NetworkResource()
	ReadOnly _shareName As String
	Private _status As ResultWin32 = New ResultWin32()
	Private _disposedValue As Boolean

	Public ReadOnly Property IsDriveMapped() As Boolean
		Get
			Dim drive = (From di In DriveInfo.GetDrives()
						 Where di.DriveType = DriveType.Network AndAlso
							 di.Name.Equals($"{_driveLetter}\")
						 Select di).FirstOrDefault()
			Return drive IsNot Nothing
		End Get
	End Property

	Public ReadOnly Property DriveLetter() As String
		Get
			Return _driveLetter
		End Get
	End Property

	Public ReadOnly Property ShareName() As String
		Get
			Return _shareName
		End Get
	End Property

	Public ReadOnly Property Status() As ResultWin32
		Get
			Return _status
		End Get
	End Property

	Public Sub New(shareName As String)
		Me.New(shareName, Nothing, Nothing)
	End Sub

	Public Sub New(shareName As String, credentials As NetworkCredential)
		Me.New(shareName, Nothing, credentials)
	End Sub

	Public Sub New(shareName As String, driveLetter As Char)
		Me.New(shareName, driveLetter, Nothing)
	End Sub

	Public Sub New(shareName As String, driveLetter As Char, credentials As NetworkCredential)
		Me.New(shareName, $"{driveLetter}:", credentials)
	End Sub

	Public Sub New(shareName As String, driveLetter As String)
		Me.New(shareName, driveLetter, Nothing)
	End Sub

	Public Sub New(shareName As String, driveLetter As String, credentials As NetworkCredential)
		If Not String.IsNullOrWhiteSpace(shareName) Then
			If shareName.Contains("\") AndAlso shareName.LastIndexOf("\") = shareName.Length - 1 Then
				shareName = shareName.Substring(0, shareName.Length - 1)
			End If
			_shareName = shareName
		Else
			Throw New ArgumentException("Share name cannot be null or empty.", "shareName")
		End If

		If Not String.IsNullOrWhiteSpace(driveLetter) Then
			If Not driveLetter.Contains(":") Then
				driveLetter = $"{driveLetter}:"
			End If
			_driveLetter = driveLetter

			If Not _driveLetter.IsDriveLetter() Then
				Throw New ArgumentException($"{_driveLetter} is not a valid drive letter.", "driveLetter")
			End If
		End If

		_networkResource = New NetworkResource() With
		{
			.Scope = ResourceScope.GlobalNetwork,
			.Type = ResourceType.Disk,
			.DisplayType = ResourceDisplayType.Share,
			.LocalName = _driveLetter,
			.RemoteName = _shareName
		}

		_credentials = credentials
	End Sub

	Public Function MapNetworkDrive() As Boolean
		If Not String.IsNullOrWhiteSpace(_driveLetter) AndAlso IsDriveMapped Then
			DisconnectNetworkDrive(True)
		End If
		_status = New ResultWin32(WNetAddConnection2(_networkResource, If(_credentials IsNot Nothing, _credentials.Password, Nothing), If(_credentials IsNot Nothing, _credentials.UserName, Nothing), 0))
		Return _status.Result = 0
	End Function

	Public Function DisconnectNetworkDrive(forceDisconnect As Boolean) As Boolean
		_status = New ResultWin32(WNetCancelConnection2(_driveLetter, 0, forceDisconnect))
		Return _status.Result = 0
	End Function

	Protected Overridable Sub Dispose(disposing As Boolean)
		If Not _disposedValue Then
			If disposing Then
				' TODO: dispose managed state (managed objects).
			End If

			DisconnectNetworkDrive(True)
		End If
		_disposedValue = True
	End Sub

	Protected Overrides Sub Finalize()
		Dispose(False)
		MyBase.Finalize()
	End Sub

	Public Sub Dispose() Implements IDisposable.Dispose
		Dispose(True)
		GC.SuppressFinalize(Me)
	End Sub
End Class

Module Extensions
	<Extension()>
	Public Function IsDriveLetter(source As String) As Boolean
		Return New Regex("[d-zD-Z]:").IsMatch(source)
	End Function
End Module

Module NativeMethods
	<DllImport("mpr.dll", CharSet:=CharSet.Unicode)>
	Public Function WNetAddConnection2(<[In]> lpNetResource As NetworkResource, <MarshalAs(UnmanagedType.LPTStr), [In]> lpPassword As String,
		<MarshalAs(UnmanagedType.LPTStr), [In]> lpUserName As String, <MarshalAs(UnmanagedType.U4), [In]> dwFlags As Int32) As <MarshalAs(UnmanagedType.U4)> Int32
	End Function

	<DllImport("mpr.dll", CharSet:=CharSet.Unicode)>
	Public Function WNetCancelConnection2(<MarshalAs(UnmanagedType.LPTStr), [In]> lpName As String, <MarshalAs(UnmanagedType.U4), [In]> dwFlags As Int32,
		<MarshalAs(UnmanagedType.Bool), [In]> fForce As Boolean) As <MarshalAs(UnmanagedType.U4)> Int32
	End Function

	Public Enum ResourceScope As Integer
		Connected = 1
		GlobalNetwork
		Remembered
		Recent
		Context
	End Enum

	Public Enum ResourceType As Integer
		Any = 0
		Disk = 1
		Print = 2
		Reserved = 8
		Unknown = -1
	End Enum

	Public Enum ResourceDisplayType As Integer
		Generic = &H0
		Domain = &H1
		Server = &H2
		Share = &H3
		File = &H4
		Group = &H5
		Network = &H6
		Root = &H7
		ShareAdmin = &H8
		Directory = &H9
		Tree = &HA
		NdsContainer = &HB
	End Enum

	<Flags>
	Public Enum ResourceUsage As Integer
		Connectable = 1
		Container = 1 << 1
		NoLocalDevice = 1 << 2
		Sibling = 1 << 3
		Attached = 1 << 4
		All = Connectable Or Container Or Attached
	End Enum

	<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)>
	Public Class NetworkResource
		<MarshalAs(UnmanagedType.U4)>
		Private _scope As ResourceScope
		<MarshalAs(UnmanagedType.U4)>
		Private _type As ResourceType
		<MarshalAs(UnmanagedType.U4)>
		Private _displayType As ResourceDisplayType
		<MarshalAs(UnmanagedType.U4)>
		Private _usage As ResourceUsage
		<MarshalAs(UnmanagedType.LPTStr)>
		Private _localName As String
		<MarshalAs(UnmanagedType.LPTStr)>
		Private _remoteName As String
		<MarshalAs(UnmanagedType.LPTStr)>
		Private _comment As String
		<MarshalAs(UnmanagedType.LPTStr)>
		Private _provider As String

		Public Property Scope As ResourceScope
			Get
				Return _scope
			End Get
			Set(value As ResourceScope)
				_scope = value
			End Set
		End Property

		Public Property Type As ResourceType
			Get
				Return _type
			End Get
			Set(value As ResourceType)
				_type = value
			End Set
		End Property

		Public Property DisplayType As ResourceDisplayType
			Get
				Return _displayType
			End Get
			Set(value As ResourceDisplayType)
				_displayType = value
			End Set
		End Property

		Public Property Usage As ResourceUsage
			Get
				Return _usage
			End Get
			Set(value As ResourceUsage)
				_usage = value
			End Set
		End Property

		Public Property LocalName As String
			Get
				Return _localName
			End Get
			Set(value As String)
				_localName = value
			End Set
		End Property

		Public Property RemoteName As String
			Get
				Return _remoteName
			End Get
			Set(value As String)
				_remoteName = value
			End Set
		End Property

		Public Property Comment As String
			Get
				Return _comment
			End Get
			Set(value As String)
				_comment = value
			End Set
		End Property

		Public Property Provider As String
			Get
				Return _provider
			End Get
			Set(value As String)
				_provider = value
			End Set
		End Property
	End Class
End Module

Class ResultWin32
	ReadOnly _result As Integer

	Public ReadOnly Property Result() As Integer
		Get
			Return _result
		End Get
	End Property

	Public ReadOnly Property GetErrorName() As String
		Get
			Dim result = (From field In Me.GetType().GetFields()
						  Where CType(field.GetValue(Nothing), Integer) = _result
						  Select field.Name).FirstOrDefault()
			Return If(Not String.IsNullOrWhiteSpace(result), result, String.Empty)
		End Get
	End Property

	Public Sub New()
	End Sub

	Public Sub New(result As Integer)
		_result = result
	End Sub

	Const ERROR_SUCCESS As Integer = 0
	Const CONNECT_UPDATE_PROFILE As Integer = &H1
	Const RESOURCETYPE_DISK As Integer = &H1
	Const RESOURCETYPE_PRINT As Integer = &H2
	Const RESOURCETYPE_ANY As Integer = &H0
	Const RESOURCE_CONNECTED As Integer = &H1
	Const RESOURCE_REMEMBERED As Integer = &H3
	Const RESOURCE_GLOBALNET As Integer = &H2
	Const RESOURCEDISPLAYTYPE_DOMAIN As Integer = &H1
	Const RESOURCEDISPLAYTYPE_GENERIC As Integer = &H0
	Const RESOURCEDISPLAYTYPE_SERVER As Integer = &H2
	Const RESOURCEDISPLAYTYPE_SHARE As Integer = &H3
	Const RESOURCEUSAGE_CONNECTABLE As Integer = &H1
	Const RESOURCEUSAGE_CONTAINER As Integer = &H2
	Const ERROR_ACCESS_DENIED As Integer = 5
	Const ERROR_ALREADY_ASSIGNED As Integer = 85
	Const ERROR_BAD_DEV_TYPE As Integer = 66
	Const ERROR_BAD_DEVICE As Integer = 1200
	Const ERROR_BAD_NET_NAME As Integer = 67
	Const ERROR_BAD_PROFILE As Integer = 1206
	Const ERROR_BAD_PROVIDER As Integer = 1204
	Const ERROR_BUSY As Integer = 170
	Const ERROR_CANCELLED As Integer = 1223
	Const ERROR_CANNOT_OPEN_PROFILE As Integer = 1205
	Const ERROR_DEVICE_ALREADY_REMEMBERED As Integer = 1202
	Const ERROR_DEVICE_IN_USE As Integer = 2404
	Const ERROR_EXTENDED_ERROR As Integer = 1208
	Const ERROR_INVALID_PASSWORD As Integer = 86
	Const ERROR_NO_NET_OR_BAD_PATH As Integer = 1203
	Const ERROR_NOT_CONNECTED As Integer = 2250
	Const ERROR_OPEN_FILES As Integer = 2401
End Class

Open in new window

Example of usage would be something like:
Module Module1
	Sub Main()
		Dim _networkConnection As NetworkConnection = Nothing
		Try
			_networkConnection = New NetworkConnection("\\kcfiler\pool", "Z")
			If _networkConnection.MapNetworkDrive() Then
				Console.WriteLine($"Successfully connected {_networkConnection.DriveLetter} to {_networkConnection.ShareName}")
			Else
				Console.WriteLine($"Could not connect {_networkConnection.DriveLetter} to {_networkConnection.ShareName}; {_networkConnection.Status.Result} [{_networkConnection.Status.GetErrorName}]")
			End If
		Catch ex As ArgumentException
			Console.WriteLine($"Argument Exception: {ex} [{ex.Message}]")
		Catch ex As Exception
			Console.WriteLine($"Exception: {ex} [{ex.Message}]")
		End Try
		Console.ReadLine()

		If _networkConnection IsNot Nothing Then
			If _networkConnection.DisconnectNetworkDrive(True) Then
				Console.WriteLine($"Successfully disconnected {_networkConnection.DriveLetter} from {_networkConnection.ShareName}")
			Else
				Console.WriteLine($"Could not disconnect {_networkConnection.DriveLetter} to {_networkConnection.ShareName}; {_networkConnection.Status.Result} [{_networkConnection.Status.GetErrorName}]")
			End If
			_networkConnection.Dispose()
			_networkConnection = Nothing
		End If
	End Sub
End Module

Open in new window

Which would produce the following output -Capture.PNG
-saige-
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Remote Access

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.