我需要在.NET应用程序中映射网络驱动器。 我需要使用AD用户名和密码进行身份验证。 通常我只需使用带有net use
命令的批处理文件。 如何在C#或VB.NET代码中执行此操作?
net use
命令的批处理文件来实现,但现在需要在C#或VB.NET代码中实现。我需要在.NET应用程序中映射网络驱动器。 我需要使用AD用户名和密码进行身份验证。 通常我只需使用带有net use
命令的批处理文件。 如何在C#或VB.NET代码中执行此操作?
net use
命令的批处理文件来实现,但现在需要在C#或VB.NET代码中实现。你看过这个了吗?
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);
}
- Elken''' <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