【问题标题】:How do I map a network drive that requires a username and password in .NET?如何在 .NET 中映射需要用户名和密码的网络驱动器?
【发布时间】:2010-07-07 21:02:51
【问题描述】:

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

【问题讨论】:

  • 为什么要映射驱动器?复制文件?
  • @Ed B 是的,在考虑了几秒钟之后,我们意识到我们将以不同的方式处理这个问题。
  • 好的..我所做的是在目标机器上共享一个文件夹..并模拟将文件保存在另一台机器上。设置共享时,我可以控制谁写入文件夹的权限。

标签: c# .net windows vb.net


【解决方案1】:

你看过这个吗?

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);

【讨论】:

  • 嗨,干得好,如果你把它包装在一个函数中,你可以去:private void MapDrive(string driveLetter, string UNCPath) { ProcessStartInfo processStartInfo = new ProcessStartInfo( "net.exe", string.Format(@"use {0}: {1}", driveLetter) ); Process process = Process.Start(processStartInfo); }
  • 我想在这里说明您可以发出 net use 命令没有驱动器名称,然后通过 UNC 路径访问该路径。这样您就不必担心用户可能已经映射了哪些驱动器。
  • @Tim Coker 关于不使用驱动器号的部分非常棒。希望我几年前就知道那个小宝石。
【解决方案2】:

这里有一些代码,您应该会发现它们比仅仅向控制台输出更可靠。

''' <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

【讨论】:

    猜你喜欢
    • 2010-12-04
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多