views:

75

answers:

4

I need to map a network drive from within a .NET application. I'm going to need to use an AD Username and Password to authenticate. Usually I just use a batch file with the net use command. How do I do this from within C# or VB.NET code?

+1  A: 

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

It will show you how to programmically map a drive from C# including credentials such as username and password

icemanind
+1  A: 

Have you looked at this?

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

Also, you could just use net.exe via Process.Start() and pass it the parameters you've always used...

System.Diagnostics.Process.Start("net.exe", "use K: \\Server\URI\\path\\here");
System.Diagnostics.Process p = System.Diagnostics.Process.Start(psi);
Tim Coker
A: 

Might my answer here apply to what you're attempting?

Jesse C. Slicer
A: 

Heres some code that you should find to be a bit more reliable than just shelling out to 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

Jonathan Allen