comet
Welcome to LanDen Labs
Source Code, Tools, Developer Notes and Performance Metrics

landenlabs.com

[ To Main Page ]


C#
Visual Studio Cleaner and More
v2.6 (July 2013)

VStudioCleaner

Download:

 


Content


Introduction

If you publish or share your software, or are just a neat freak and like to keep your disk clean, you will appreciate this utility to remove superfluous files. VStudio generates extra files which can be safely deleted because they are either temporary files from an upgrade or are produced when you build your solution. This utility is based off of the CodeProject "VS.NET Solution Cleaner" by Leonarddo Paneque and borrows some behavior from "Wise Cleaner". VStudioCleaner is basically a file and directory search engine which presents the results for deletion. The search 'filters' can be changed. Groups of filter settings can be associated with 'bookmarks' for quick recall. My personal hang ups with other applications are the inverse of the following features I offer and guidelines I try to adhere to when creating software.

mainscreen

This program is more than just a Visual Studio cleaner because the filters are expandable. You can create your own set of filters and bind them to a bookmark for easy recall.

Features include:

How To Use

To use VStudioCleaner you need to set the search Path to one or more directories and select one or more filters.

The search "path" can be set by either typing in the path, using TAB to auto-complete, cut&paste, drag-and-drop a path or using the Path... button to browse and select a path. If you need to specify multiple paths, you cannot use the Path... button because it does not append, it only knows how to set the search path. Multiple directory (folder) paths are specified by separating them by semicolon, as in:

		
     c:\dir1;c:\dir2\subdir1;d;\dir3\subdir2;e:\

As you type the path, you can use TAB to autocomplete the first path in a series. If the path is incomplete and therefore invalid it will draw the background path box in pink. If the path is valid, it will set the background to white.

path-completion

You set your filters by either 'checking' or 'unchecking' the built-in filters or by adding your own filters. Once the search "Path" and "Filters" are set, press the "Locate" button to build up a list of files and directories. The resulting list will appear in its own dialog. You can sort the various columns (why, directory, file, extension, size) and right-click to remove files from the list. The right-click remove action only removes the names from the list, it does not remove anything from your computer. Once you have your list of files pruned down to those you want to delete from your computer, you can press the "delete" button.

Warning - The delete action is permanent if compiled as 'Any CPU' and the description in the file scan dialog will repeat this warning. If compiled as x86 or x64 the selected files will be moved to the Recycle Bin.

How to use steps:

  1. Set path by typing path, using TAB key to auto-complete, dragging a folder path on to path box or browsing via the Path... button.
  2. Optionally set/unset filter toggles, or by double clicking on any pre-made Bookmarks to reload previously saved filter settings.
  3. Press blue Locate Files... button
step1


Once File List Dialog Appears ...

  1. You can adjust the file list by either pressing the quick 'why' toggle buttons on the left. You can also right click on them to use their menus. The why buttons will hide or restore all of the files which match a filter by their why name, which appears in the first column of the tabular file list. When you hover over why button, the tool tip help while state its why name. The number on the button is the number of items in the specific why collection. For example, the first white button is the Suo why collection. The 2nd button which is light green with 20 on it, is the Bin why collection, etc.


  1. In addition to the why buttons, you can use the Selection Filter box to select files by using a search pattern or by multi selecting rows in the tabular file list. Right click to open the context menu to remove the selected files from the list. Remove does not delete the files, it just removes them from the file list. You can also open explorer or open a cmd window at a file location. Lastly you can force the selected files to be delete from the disk NOW.


  1. When you are happy with the list of files, press the Delete Files button. The files will either be permanently deleted or moved to the Recycle Bin. The action depends on how the executable was built. The action is documented in the white text on the bottom of the top banner. The executable I provide will delete files by moving them to the recycle bin. After pressing the Delete Files button you get one last chance to change your mind via the confirmation dialog.


  1. While the files are being deleted (or moved to recycle bin), they are removed from the file list. The progress bar shows how far the process has gone and the File and Space totals are updated.

    If you change your mind you can Stop the deletion but it will not automatically restore any deleted files. If the files were moved to the Recycle Bin, you can restore the files via the Windows Recycle Bin icon.



Filters Rules and Bookmarks

Filters are patterns used to select directories and files. Filters fall into four categories:
1. Directory names, match directory and select all files and subdirectories
2. File extensions, matches files
3. Wildcard, matches directories and files
4. Exclude files or directories

  1. Directory filters must end in a back slash. Example: debug\
    Directory filters only match on directory names and cause the directory and all of its subdirectories and files to be selected.

  2. File extension must start with a dot. Example: .obj
    File extension filter only matches files.

  3. Wildcard filter is a collection of characters which includes one or more wildcard characters "*". Each wildcard can appear multiple times.
    
            *    Matches zero or more characters.
    Example: Connect*.xml Matches: Connect.xml Connection.xml Example: *foo*bar.* Matches: foobar. 1foo2bar.car foofoobar.x
    The wildcard filter is tested against the full file or directory path so it is common for all wildcard patterns to start with * to match any prefix of disk drive letters and directories.

            Example (* match shown in bold)
    
            Pattern                   Test Against                             Results
            --------------------      ----------------------------------       ----------
            *foo                      c:\alpha\beta\foo                        match
            *foo\bin\*                c:\foo\junk                              no match
            *foo\bin\*                c:\foo\bin\                              match
            *foo\bin\*                c:\alpha\foo\bin\                        match
            *\bin\*.obj               c:\foo\bar\bin\car.obj                   match
            *\bin\*.o*                c:\foo\bar\bin\car.old                   match
            *\bin\*.o*                d:\bin\junk.obj                          match
        
    A filter can contain one or more filters separated by semicolons. Example: Connect*.xml;.obj;obj\

  4. The exclude filter is evaluated last. Exclude filter starts with a minus sign. Example: -*.exe

    The above example will match on the directory bin and all of its subdirectories and files. The exclude pattern will exclude all files with extension .exe from the matched files. NOTE: The exclude only works on File and Wildcard filters and not simple Directory name filters. The following will not work because the members of bin directory are not tested individually.

    
        Example:  bin\;-*.exe 
        
Special Global Exclude Filters

If one or more exclude filters have their Filter name set to 'never', they are always evaluated to prevent files from being located. Remember to start the filter pattern with a minus sign.

Example:
Filter Details Description
never-exe -*.exe Don't remove executables
never-cpp -*.cpp Don't remove source files cpp
never-zed -*\Zed*\* Don't remove Zed graph directories

Use Add and Delete buttons to manage your collection of filter rules.
Double click on a row to change its value.
Right click if you want to Export the filter rules as CSV
Filter names must be unique. Duplicate filters will be ignored next time you restart.


Bookmarks

Use the bookmarks to memorize a set of filter rule checkmark state setting. Use the bookmark Add Bmark button to add a new bookmark to remember the current settings. Double Click on a bookmark to activate its settings. Press the Set Bmark button to refresh the current state of a selected bookmark to the current list of active filter rules and Path.


Screen/Menu Samples

Sample screen showing Read-only toggle button.

readonly


Sample screen of File and Directory List showing context menu.

selectedscreen



Warning

As of version 2.5, the file and directory delete action has been changed to move files to the recycle bin. This only works if the code is compiled as either x86 or x64. If it is compiled as Any CPU the recycle bin code crashes so I disabled it and any file deletion is permanent. The notice text in the top banner will state if the files are moved to recycle or permantently deleted.

No undo to restore items removed from the file list. But if you use the why toggle buttons on the left, they can hide and restore the group of files.


Points of Interest

While writing this application I learned the following:

1. How to launch RegEdit and get it to open on a specific registry entry
2. How to force a listview to scroll to the left
3. Registering VStudioCleaner on Explorer's Folder menu.
4. Recursive pattern matcher
5. Inline html help text
6. Enhanced Folder browser

1. If you need to open RegEdit at specific location you can use this trick. RegEdit like most Windows applications saves its session settings in the registry. Before you launch RegEdit you simply set the value of LastKey in section Software\Microsoft\Windows\CurrentVersion\Applets\Regedit to the registry path you want to open on. When you start RegEdit it will automatically open at LastKey location.

  	  
      private void openRegistry_Click(object sender, EventArgs e)
      {
          string appName = Application.ProductName;

          // Preset last place RegEdit visited to our registry section
          RegistryKey regEditKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Applets\Regedit");
          regEditKey.SetValue("LastKey", @"My Computer\HKEY_CURRENT_USER\Software\" + appName);
          regEditKey.Close();

          // Launch RegEdit which will default at the last place it was (our stuff).
          System.Diagnostics.Process.Start("regedit.exe");
      }

2. The second trick "to scroll listview left" was required when a user is editing a row in a ListView. Depending on the size of the UI, it is possible that part of the row is not visible. Before a column is edited, I wanted it to be in view so I had to scroll it to the left. Here is code I use to send keys to the UI in focus.


    for (int i = 0; i < shift; i++)
    {
        SendKeys.Send("{RIGHT}");
        SendKeys.Flush();
    }

3. VStudioCleaner can be registered to appear in the Explorer Folder popup menu.

Example of VStudioCleaner's Option menu showing register choices:

screen4


Sample screen showing Explorer integrated VStudioCleaner menu to launch on a folder menu.

explorer-menu

It took some looking to find how to get the Explorer menu to show an icon next to my program in the Folder Popup menu. The trick was to add the Icon key to the registry entry. The following code works in Windows 7.

registry
Here is the code which adds VStudioCleaner to Explorer's folder popup menu (Windows 7).
private void Register()
{
    string appName = Application.ProductName;
    string RegShell = RegFolderShell + appName;
    string Command = RegShell + "\\command";

    RegistryKey regmenu = null;
    RegistryKey regcmd = null;
    try
    {
        regmenu = Registry.ClassesRoot.CreateSubKey(RegShell);
        if (regmenu != null)
            regmenu.SetValue("", "Clear using " + appName);
        regcmd = Registry.ClassesRoot.CreateSubKey(Command);
        if (regcmd != null)
            regcmd.SetValue("", Environment.CommandLine + "\x22%1\x22");
        regmenu.SetValue("Icon", Environment.CommandLine.Trim().Replace("\x22", ""));
        regmenu.SetValue("MUIVerb", "VStudioCleaner");      // &Open, ...
    }
    catch (Exception ex)
    {
        throw new Exception("Problem registering application on Explorer menu " + ex.Message);
    }
    finally
    {
        if (regmenu != null)
            regmenu.Close();
        if (regcmd != null)
            regcmd.Close();
    }
}
Once VStudioCleaner is register to the shell folders, you can right click on a folder and easily launch VStudioCleaner on that folder. The folder path will appear as its default search path.


4. This program also includes a simple wildcard pattern matching engine. It only supports a single specialized wildcard '*' but the wildcard can appear multiple times in the pattern. The details on using the pattern matcher are found in the previous Filters Rules section.

        /// <summary>
        /// WildCompare supports simple '*' wildcard pattern.
        /// Returns true if pattern matches even if raw text has more characters.
        /// </summary>
        /// <returns> true for partial match</returns>
        private bool WildCompare(string wildStr, int wildOff, string rawStr, int rawOff)
        {
            while (wildOff != wildStr.Length)
            {
                if (rawOff == rawStr.Length)
                    return (wildStr[wildOff] == '*');

                if (wildStr[wildOff] == '*')
                {
                    if (wildOff + 1 == wildStr.Length)
                        return true;

                    do
                    {
                        // Find match with char after '*'
                        while (rawOff < rawStr.Length &&
                            char.ToLower(rawStr[rawOff]) != char.ToLower(wildStr[wildOff + 1]))
                            rawOff++;
                        if (rawOff < rawStr.Length &&
                            WildCompare(wildStr, wildOff + 1, rawStr, rawOff))
                            return true;
                        ++rawOff;
                    } while (rawOff < rawStr.Length);

                    if (rawOff >= rawStr.Length)
                        return (wildStr[wildOff + 1] == '*');
                }
                else
                {
                    if (char.ToLower(rawStr[rawOff]) != char.ToLower(wildStr[wildOff]))
                        return false;
                    if (wildStr.Length == wildOff)
                        return true;
                    ++rawOff;
                }

                ++wildOff;
            }

            return true;
        }

5. Because the pattern matching is complex I added a popup help dialog, launched by pressing the "?" button. The original version used a RichTextBox. I found it painful to setup font size and colorization, so I switched in version v1.5 to HTML. I wanted to keep VStudioCleaner a single program and did not want a CHM or HTML help file. I discovered I could embedded the HTML in the program. The tricky part is to encode the images into the HTML which in turn is embedded in the executable producing a single file VStudioCleaner.exe with a nice color illustrated help file. The images are encoded in the HTML by converting them to base64. See my article on Code Project "Embedded HTML Help File with Images"


6. The standard C# Folder Browser dialog is very boring. I found a replacement version here: http://support.microsoft.com/default.aspx?scid=kb;[LN];306285 The code also includes another MS version but it requires DLL's and per one of my personal requirements, this program needs to be a single executable with no auxilary files required so I did not use the DLL version.


Final Word

This program and similar programs with their source code are available on Dennis Lang's Source code and Performance Metrics web site:

https://landenlabs.com//
This article is also publish on codeproject:
http://www.codeproject.com/KB/cs/visual_studio_cleaner.aspx

I want to thank Leonardo Paneque for providing his CodeProject "Solution Cleaner". His home page is:

http://www.teknowmagic.net/

A similar product is available from WiseCleaner:

https://www.wisecleaner.com/wise-disk-cleaner.html
And a related tool which instead of cleaning the junk out, does the opposite. It zip's up the good stuff leaving the directories untouched. CleanProject by Ron Jacobs (Microsoft).
http://visualstudiogallery.msdn.microsoft.com/bca632e0-3948-43c8-b337-da47275717b6


Revision History

  • Aug 23, 2009 v1.4
  • Aug 30, 2009 v1.5
  • Sep 13, 2009 v1.6
  • Dec 17, 2011 v1.8
  • Dec 22, 2011 v1.9
  • June 1, 2013 v2.5
  • Top

    Blog about Visual Studio Cleaner