Click here to Skip to main content
15,889,874 members
Articles / Programming Languages / C#
Tip/Trick

Win7: Reconnect Network Mapped Drives

Rate me:
Please Sign up or sign in to vote.
4.33/5 (2 votes)
17 Apr 2012CPOL 19.2K   5   2
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)


Written By
Software Developer
United States United States
likes boardgames, computer games, and enjoys his .net programming job.

Comments and Discussions

 
QuestionBrilliant Pin
masteripper29-Nov-18 9:45
masteripper29-Nov-18 9:45 
GeneralMy vote of 3 Pin
wibleywoo3-Apr-14 0:08
wibleywoo3-Apr-14 0:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.