How to create a map using C #?

How to map a network drive using C #. I do not want to use net use or any third-party API.

I heard about UNC paths in C # code, but I'm not quite sure how to do this.

+7
c #
source share
4 answers

Use the WnetAddConnection functions available in native mpr.dll .

You will need to write P / Invoke signatures and structures to call an unmanaged function. You can find resources on P / Invoke at pinvoke.net .

This is the signature for WNetAddConnection2 on pinvoke.net :

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

A more straightforward solution is to use 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; } } 

After you went above, use below, if necessary, create / delete a mapped drive.

 Converter.RunProcess("net.exe", @"use Q: \\server\share", null); Converter.RunProcess("net.exe", "use Q: /delete", null); 
+2
source share

Check out the NetShareAdd Windows API. Of course, you will need to use PInvoke to, of course, get it.

0
source share

There is no standard function in .net for mapping network drives, but here you can find a good shell if you do not want to make your own calls yourself: http://www.codeguru.com/csharp/csharp/cs_network/windowsservices/article.php / c12357

0
source share

All Articles