2010-08-12 64 views
7

¿Cómo puedo mapear una unidad de red usando C#. No quiero usar net use ni ninguna API de terceros.Cómo mapear una unidad usando C#?

He oído hablar de las rutas UNC en el código C# pero no estoy seguro de cómo hacerlo.

Respuesta

7

Utilice las funciones WnetAddConnection disponibles en el mpr.dll nativo.

Deberá escribir las firmas y las estructuras P/Invocar para llamar a la función no administrada. Puede encontrar recursos en P/Invoke en pinvoke.net.

Ésta es the signature for WNetAddConnection2 on pinvoke.net:

[DllImport("mpr.dll")]  
public static extern int WNetAddConnection2(
    ref NETRESOURCE netResource, 
    string password, 
    string username, 
    int flags); 
0

Echa un vistazo @ a la API de Windows NetShareAdd. Necesitarás usar PInvoke para tenerlo en tus manos, por supuesto.

+4

'NetShareAdd' crea una cuota. La pregunta es acerca de cómo mapear un recurso compartido existente. –

2

solución más recta hacia adelante es usar 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; 
    } 
} 

Una vez que tenga todo lo anterior, a continuación utilizar crear/borrar unidad mapeada según sea necesario.

Converter.RunProcess("net.exe", @"use Q: \\server\share", null); 

Converter.RunProcess("net.exe", "use Q: /delete", null); 
+0

Versión más simple: asegúrese de estar "usando System.Diagnostics"; para System.Diagnostics.Process: \t CHAR LetraDeUnidad = 'R'; '' \t string path = @ "\\ Contoso \ share \ cosas"; '' \t Process.Start (nueva ProcessStartInfo (@ "C: \ Windows \ System32 \ net.exe "," use "+ DriveLetter +": "+ Ruta de acceso)); – omJohn8372

Cuestiones relacionadas