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
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 { }
}
}
}
}