Map network drive programmatically in C# on Windows 10

前端 未结 3 1645
闹比i
闹比i 2021-01-02 02:52

I followed the approache to map a network drive programmatically in the following link: Mapping Network Drive using C#

The drive seems to be connected correctly beca

相关标签:
3条回答
  • 2021-01-02 03:12

    Mapped drives can be very confusing. The issue is that they only appear for the "user" that created them. This was hinted at in the question in the comments about UAC and Run as Administrator.

    IF you "Run As" whoever, then the drives will only appear for that whoever.

    If you are only worried about User vs Elevated user access, there is a registry key to enable this: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System

    EnableLinkedConnections

    Please see this for more details: https://docs.microsoft.com/en-us/troubleshoot/windows-client/networking/mapped-drives-not-available-from-elevated-command

    0 讨论(0)
  • 2021-01-02 03:21

    Resting my laptop seemed to fix whatever problem windows had. All three approaches below are working like a charm. My favorite one is of course the C# "only" approach.

    // Approach 1
    Utility.NetworkDrive.MapNetworkDrive("R", @"\\unc\path");
    var dirs1 = Directory.GetDirectories("R:");
    Utility.NetworkDrive.DisconnectNetworkDrive("R", true);
    
    // Approach 2
    DoProcess("net", @"use R: \\unc\path");
    var dirs2 = Directory.GetDirectories("R:");
    DoProcess("net", "use /D R:");
    
    // Approach 3
    DoProcess("cmd", @"/c C:\local\path\to\batch\connect.cmd");
    var dirs3 = Directory.GetDirectories("R:");
    DoProcess("cmd", @"/c C:\local\path\to\batch\diconnect.cmd");
    
    public static string DoProcess(string cmd, string argv)
    {
        Process p = new Process();
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.FileName = cmd;
        p.StartInfo.Arguments = $" {argv}";
        p.StartInfo.CreateNoWindow = true;
        p.Start();
        p.WaitForExit();
        string output = p.StandardOutput.ReadToEnd();
        p.Dispose();
    
        return output;
    }
    
    0 讨论(0)
  • 2021-01-02 03:23

    If you are using @Mario's Approach 2 and want to keep the drive then remove the following line:

    DoProcess("net", "use /D R:");
    
    0 讨论(0)
提交回复
热议问题