如何在.NET中映射需要用户名和密码的网络驱动器?

10

我需要在.NET应用程序中映射网络驱动器。 我需要使用AD用户名和密码进行身份验证。 通常我只需使用带有net use命令的批处理文件。 如何在C#或VB.NET代码中执行此操作?

我需要在.NET应用程序中通过AD用户名和密码映射网络驱动器。通常情况下,我使用带有net use命令的批处理文件来实现,但现在需要在C#或VB.NET代码中实现。

你为什么要映射驱动器?是为了复制文件吗? - Ed B
@Ed B 是的,在多想几秒钟后,我们意识到我们会用不同的方式来处理这个问题。 - Ben McCormack
好的,我的做法是在目标机器上共享一个文件夹,并进行模拟以保存到另一台机器上。我可以在设置共享时控制谁有写入文件夹的权限。 - Ed B
2个回答

15

你看过这个了吗?

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

另外,你可以通过 Process.Start() 直接使用 net.exe 并传递你在下面代码中一直使用的参数:

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

这也可以在没有驱动器字母的情况下使用,并通过 UNC 路径访问。

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

1
你好,做得很不错,如果你将它包装到一个函数里面,可以像这样:private void MapDrive(string driveLetter, string UNCPath) { ProcessStartInfo processStartInfo = new ProcessStartInfo( "net.exe", string.Format(@"use {0}: {1}", driveLetter) ); Process process = Process.Start(processStartInfo); } - Elken
1
我想在这里提一下,你可以使用net use命令而不带驱动器名称然后通过UNC路径访问路径。这样你就不必担心用户可能已经映射了哪些驱动器。 - Tim Coker
1
@Tim Coker 关于不使用驱动器号的部分真是太棒了。但愿我多年前就知道这个小技巧了。 - MatthewD

0
这里有一些代码,你会发现它比仅仅在控制台中运行更可靠。
''' <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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接