Everything about my daily life as a programmer/Electrical Engineer!

C# Code to cleanup Startmenu

I image my machine once a semester to clear off all the garbage I installed over the term. (I use partimage in case anyone cares).  Anyway I always have unsused shortcuts left in my startmenu since that lives on my d:\ drive which is where my data and profile are.  I wrote the code below to nuke bad shortcuts and empty shortcut directories.  It doesn't get all the uninstall files and readme links but its good enough!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using IWshRuntimeLibrary;

namespace ConsoleApplication12
{
class Program
{
static void Main(string[] args)
{
string path = @"D:\Michael\Start Menu\";

WshShell shell = new WshShell();
string[] files = Directory.GetFiles(path, "*.lnk", SearchOption.AllDirectories);
Directory.CreateDirectory(@"C:\oldshortcuts");
List<string> directories = new List<string>();
foreach (string file in files)
{
IWshShortcut link = shell.CreateShortcut(file) as IWshShortcut;
if (!System.IO.File.Exists(link.TargetPath))
{
Console.Write("Broken Shortcut");
Console.WriteLine(file);
directories.Add(Path.GetDirectoryName(file));
try
{
System.IO.File.Copy(file, Path.Combine("C:\\oldshortcuts", Path.GetFileName(file)), true);
System.IO.File.Delete(file);
}
catch { Console.WriteLine("Error copying file and deleting file. Press any key to continue"); Console.ReadLine(); }
}
}
//now delete the old shortcuts
foreach (string dir in directories)
{
if (!Directory.Exists(dir)) { continue; }//we already deleted this!
DirectoryInfo info = new DirectoryInfo(dir);
if (info.GetFiles("*", SearchOption.AllDirectories).Length == 0)
{
try
{
info.Delete(true);
Console.Write("Deleting directory");
Console.WriteLine(info.FullName);
}
catch { Console.WriteLine("Error Removing Directory. Press any key to continue"); Console.ReadLine(); }
}
}


}
}
}

2 comments:

Kris Mok said...

Hi,
Why have "C:\\oldshortcuts" and @"C:\\oldshortcuts"? You meant to use @"C:\oldshortcuts", right?
And umm, Directory.Delete(string) will do the delete fine, because it only deletes empty exisiting directories. Wrap that with a try-catch block and you're there. :)

Michael said...

Good call, I'll make that change soon. Thanks!