如何使用C#映射驱动器?
使用本地mpr.dll
中的WnetAddConnection
功能。
您将必须编写P/Invoke签名和结构来调用非托管函数。您可以在pinvoke.net上的P/Invoke上找到资源。
这是the signature for WNetAddConnection2
on pinvoke.net:
[DllImport("mpr.dll")]
public static extern int WNetAddConnection2(
ref NETRESOURCE netResource,
string password,
string username,
int flags);
有一个在.NET中没有标准的功能映射networkdrives,但你可以在这里找到一个很好的包装,如果你不想自己来执行本地电话:http://www.codeguru.com/csharp/csharp/cs_network/windowsservices/article.php/c12357
更直接的解决方案是使用Process.Start()
internal static int RunProcess(string fileName, string args, string workingDir)
{
var startInfo = new ProcessStartInfo
{
FileName = fileName,
Arguments = args,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
CreateNoWindow = true,
WorkingDirectory = workingDir
};
using (var process = Process.Start(startInfo))
{
if (process == null)
{
throw new Exception($"Failed to start {startInfo.FileName}");
}
process.OutputDataReceived += (s, e) => e.Data.Log();
process.ErrorDataReceived += (s, e) =>
{
if (!string.IsNullOrWhiteSpace(e.Data)) { new Exception(e.Data).Log(); }
};
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
return process.ExitCode;
}
}
一旦你有以上,使用下面创建/删除根据需要映射驱动器。
Converter.RunProcess("net.exe", @"use Q: \\server\share", null);
Converter.RunProcess("net.exe", "use Q: /delete", null);
简化版本 - 确保您使用System.Diagnostics;为的System.Diagnostics.Process: \t'炭驱动器号= 'R';' \t'串路径= @ “\\ CONTOSO \共享\物”;' \t'的Process.Start(新的ProcessStartInfo(@“C: \ Windows \ System32 \ net.exe“,”使用“+ DriveLetter +”:“+ Path));' – omJohn8372 2017-04-05 19:02:35
'NetShareAdd'创建共享。问题是关于如何映射现有份额。 – 2010-08-12 09:19:57