How to map a network drive that requires a username and password in .NET?

I need to map a network drive from a .NET application. I will need to use the AD username and password for authentication. Usually I just use a batch file with the net use command. How to do it from C # or VB.NET code?

+10
c # windows
source share
3 answers

Have you looked at it?

http://www.codeguru.com/csharp/csharp/cs_network/windowsservices/article.php/c12357

Alternatively, you can simply use net.exe through Process.Start() and pass parameters to it that you always used in the code below:

 System.Diagnostics.Process.Start("net.exe", "use K: \\\\Server\\URI\\path\\here"); 

It can also be used without a drive letter, and then accessed via the UNC path.

  System.Diagnostics.Process.Start("net.exe", @"use @"\\Server\URI\path\here"); System.IO.File.Copy(@"\\Server\URI\path\here\somefile.abc", destFile, true); 
+14
source share

See this site: http://www.blackwasp.co.uk/MapDriveLetter.aspx

It will show you how to program the card with C #, including credentials like username and password

+8
source share

Here is the code you should find that is a little more reliable than just shelling the console.

 ''' <summary> ''' ''' </summary> ''' <param name="driveLetter"></param> ''' <param name="uncName"></param> ''' <remarks>This was hand tested. We cannot automate because it messes with the OS</remarks> Sub MapDrive(ByVal driveLetter As Char, ByVal uncName As String) Dim driveLetterFixed = Char.ToLower(driveLetter) If driveLetterFixed < "a"c OrElse driveLetterFixed > "z"c Then Throw New ArgumentOutOfRangeException("driveLetter") If uncName Is Nothing Then Throw New ArgumentNullException("uncName") If uncName = "" Then Throw New ArgumentException("uncName cannot be empty", "uncName") Dim fixedUncName As String = uncName 'This won't work if the unc name ends with a \ If fixedUncName.EndsWith("\") Then fixedUncName = fixedUncName.Substring(0, fixedUncName.Length - 1) Dim oNetWork As New IWshRuntimeLibrary.IWshNetwork_Class Try 'This usually isn't necessary, but we can't detect when it is needed. oNetWork.RemoveNetworkDrive(driveLetter, True, True) Catch ex As Runtime.InteropServices.COMException 'Ignore errors, it just means it wasn't necessary End Try oNetWork.MapNetworkDrive(driveLetter, fixedUncName, True) End Sub 

http://clrextensions.codeplex.com/SourceControl/changeset/view/55677#666894

0
source share

All Articles