2010-08-12 107 views

回答

0

看一看@NetShareAdd Windows的API。當然,您需要使用PInvoke來實現它。

+4

'NetShareAdd'創建共享。問題是關於如何映射現有份額。 – 2010-08-12 09:19:57

2

更直接的解決方案是使用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); 
+0

簡化版本 - 確保您使用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