Tuesday, 22 July 2014

Mapping a network drive in C#

         

            string path = @"\\IPADDRESS /user:DOMAIN\USERNAME PASSWORD";
            // Z is the name given to the mapped network drive
            string strMapDrive = "/C net use Z: " + path;
            string strUnMapDrive = "/C net use Z: /delete";
            if (Directory.Exists("Z:\\"))
            {
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                startInfo.FileName = "cmd.exe";
                startInfo.Arguments = strUnMapDrive;
                process.StartInfo = startInfo;
                process.Start();
                startInfo.Arguments = strMapDrive;
                process.StartInfo = startInfo;
                process.Start();
            }