Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Win7: Reconnect Network Mapped Drives

4.33/5 (2 votes)
17 Apr 2012CPOL 19.4K  
Script to reconnect Windows mapped drives (Win7).

Introduction

Windows 7 doesn't always reconnect network drives when you restart. This code will go through and try to reconnect any mapped drives. If you have any problems with it, let me know. 

For Windows Vista / XP, the process may have a different format for the Window title, so you'll have to test/change it for different operating systems. 

Why not just Kill the process that you start? The original process you create when calling Process.Start opens another process and then ends. 

Code 

C#
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;

namespace RestartMappedDrives {
    class Program {
        static void Main(string[] args) {
            var p = Process.Start(new ProcessStartInfo { FileName = "net", 
                    Arguments = "use", RedirectStandardOutput = true, UseShellExecute = false });
            var str = p.StandardOutput.ReadToEnd();
            foreach (string s in str.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)) {
                var s2 = s.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                if (s2.Length >=2 && s2[1][1] == ':')
                    Map(s2[1][0].ToString());
            }
        }

        private static void Map(string drive) {
            if (!new DriveInfo(drive).IsReady) {
                try {
                    Process.Start(new ProcessStartInfo { FileName = "explorer", 
                           Arguments = drive + ":\\", WindowStyle = ProcessWindowStyle.Minimized });
                    Thread.Sleep(500);
                    foreach (Process p in Process.GetProcessesByName("explorer")) {
                        if (p.MainWindowTitle.EndsWith(@"(" + drive + ":)", 
                                    StringComparison.CurrentCultureIgnoreCase)) {
                            p.Kill();
                        }
                    }
                } catch { }
            }
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)