Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map network drive programmatically in C# on Windows 10

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 because I can query directories and files within C#. BUT I do not see the drive on my computer. My target is to map certain drives programmatically for my users. I don'T want to use batch/cmd... Is there maybe a problem with windows 10 or is this code just good for programming approaches.

Kind Regards

Use of code:

Utility.NetworkDrive.MapNetworkDrive("R", @"\\unc\path");
var dirs = Directory.GetDirectories("R:"); // got many nice directories...
Utility.NetworkDrive.DisconnectNetworkDrive("R", true);

Full Code:

namespace Utility
{
    public class NetworkDrive
    {
        private enum ResourceScope
        {
            RESOURCE_CONNECTED = 1,
            RESOURCE_GLOBALNET,
            RESOURCE_REMEMBERED,
            RESOURCE_RECENT,
            RESOURCE_CONTEXT
        }
        private enum ResourceType
        {
            RESOURCETYPE_ANY,
            RESOURCETYPE_DISK,
            RESOURCETYPE_PRINT,
            RESOURCETYPE_RESERVED
        }
        private enum ResourceUsage
        {
            RESOURCEUSAGE_CONNECTABLE = 0x00000001,
            RESOURCEUSAGE_CONTAINER = 0x00000002,
            RESOURCEUSAGE_NOLOCALDEVICE = 0x00000004,
            RESOURCEUSAGE_SIBLING = 0x00000008,
            RESOURCEUSAGE_ATTACHED = 0x00000010
        }
        private enum ResourceDisplayType
        {
            RESOURCEDISPLAYTYPE_GENERIC,
            RESOURCEDISPLAYTYPE_DOMAIN,
            RESOURCEDISPLAYTYPE_SERVER,
            RESOURCEDISPLAYTYPE_SHARE,
            RESOURCEDISPLAYTYPE_FILE,
            RESOURCEDISPLAYTYPE_GROUP,
            RESOURCEDISPLAYTYPE_NETWORK,
            RESOURCEDISPLAYTYPE_ROOT,
            RESOURCEDISPLAYTYPE_SHAREADMIN,
            RESOURCEDISPLAYTYPE_DIRECTORY,
            RESOURCEDISPLAYTYPE_TREE,
            RESOURCEDISPLAYTYPE_NDSCONTAINER
        }
        [StructLayout(LayoutKind.Sequential)]
        private struct NETRESOURCE
        {
            public ResourceScope oResourceScope;
            public ResourceType oResourceType;
            public ResourceDisplayType oDisplayType;
            public ResourceUsage oResourceUsage;
            public string sLocalName;
            public string sRemoteName;
            public string sComments;
            public string sProvider;
        }
        [DllImport("mpr.dll")]
        private static extern int WNetAddConnection2
            (ref NETRESOURCE oNetworkResource, string sPassword,
            string sUserName, int iFlags);

        [DllImport("mpr.dll")]
        private static extern int WNetCancelConnection2
            (string sLocalName, uint iFlags, int iForce);

        public static void MapNetworkDrive(string sDriveLetter, string sNetworkPath)
        {
            //Checks if the last character is \ as this causes error on mapping a drive.
            if (sNetworkPath.Substring(sNetworkPath.Length - 1, 1) == @"\")
            {
                sNetworkPath = sNetworkPath.Substring(0, sNetworkPath.Length - 1);
            }

            NETRESOURCE oNetworkResource = new NETRESOURCE()
            {
                oResourceType = ResourceType.RESOURCETYPE_DISK,
                sLocalName = sDriveLetter + ":",
                sRemoteName = sNetworkPath
            };

            //If Drive is already mapped disconnect the current 
            //mapping before adding the new mapping
            if (IsDriveMapped(sDriveLetter))
            {
                DisconnectNetworkDrive(sDriveLetter, true);
            }

            WNetAddConnection2(ref oNetworkResource, null, null, 0);
        }

        public static int DisconnectNetworkDrive(string sDriveLetter, bool bForceDisconnect)
        {
            if (bForceDisconnect)
            {
                return WNetCancelConnection2(sDriveLetter + ":", 0, 1);
            }
            else
            {
                return WNetCancelConnection2(sDriveLetter + ":", 0, 0);
            }
        }

        public static bool IsDriveMapped(string sDriveLetter)
        {
            string[] DriveList = Environment.GetLogicalDrives();
            for (int i = 0; i < DriveList.Length; i++)
            {
                if (sDriveLetter + ":\\" == DriveList[i].ToString())
                {
                    return true;
                }
            }
            return false;
        }

    }

}
like image 786
Mario Avatar asked Apr 02 '17 21:04

Mario


People also ask

Can you map a network drive from the command line?

“Net use” is a command line method of mapping network drives to your local computer.

How do I map a drive using an IP address?

Windows ExplorerRight click on My Computer / Select Map Network Drive. Select the drive you would like to map from. In the folder field, you can enter the address manually (format: \\address), click from the drop down box to select the address or browse to select the folder.


2 Answers

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;
}
like image 89
Mario Avatar answered Sep 22 '22 02:09

Mario


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

like image 36
machinefreak Avatar answered Sep 20 '22 02:09

machinefreak