代码之家  ›  专栏  ›  技术社区  ›  Simsons

如何使用c_映射驱动器?

  •  7
  • Simsons  · 技术社区  · 14 年前

    如何使用c_映射网络驱动器。我不想用 net use 或任何第三方API。

    在C代码中听说过UNC路径,但不太确定如何处理它。

    4 回复  |  直到 8 年前
        1
  •  8
  •   Uwe Keim    11 年前

    使用 WnetAddConnection 在本机中可用的函数 mpr.dll .

    必须编写P/Invoke签名和结构才能调用非托管函数。您可以在上的p/invoke上找到资源 pinvoke.net .

    这是 the signature for WNetAddConnection2 on pinvoke.net :

    [DllImport("mpr.dll")]    
    public static extern int WNetAddConnection2(
       ref NETRESOURCE netResource,
       string password, 
       string username, 
       int flags);
    
        2
  •  1
  •   WiSeeker    8 年前

    更直接的解决方案是使用 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);
    
        3
  •  0
  •   Will A    14 年前

    看看 NetShareAdd Windows的API。当然,你需要用松鸡来控制它。

        4
  •  0
  •   Wouter Janssens    14 年前

    .NET中没有映射NetworkDrives的标准功能,但是如果不想自己执行本机调用,可以在此处找到一个好的包装器: http://www.codeguru.com/csharp/csharp/cs_network/windowsservices/article.php/c12357