Click here to Skip to main content
15,860,859 members
Articles / Programming Languages / C#

Visual Studio Cleaner and More

Rate me:
Please Sign up or sign in to vote.
4.86/5 (17 votes)
18 Dec 2011CPOL7 min read 59.8K   2.4K   55   21
Delete junk files from Visual Studio solution/project by selecting files using search patterns
vstudiocleaner-exe

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. Visual Studio generates extra files which can be safely deleted because they are either automatically generated or are produced when you build your solution. This utility is based off of the CodeProject "VS.NET Solution Cleaner" by Leonardo 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.

  1. All dialogs should allow resizing (and look good when size is increased) 
  2. Avoid modal dialogs
  3. List/tables should support column sorting and multiple selection
  4. Drag and Drop (though this app has no specialized implementation)
  5. Export - make it easy to export information in a simple form (Text or CSV) 
  6. Remember configuration changes 
  7. Ideally the program should be a single executable

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. You can use it to cleanup your browser droppings.

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, cut & paste 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:\

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. The files will NOT appear in the Recycle Bin.

Filters

Filters are patterns used to select directories and files. Filters fall into three categories:

  1. Directory names, match directory and select all files and subdirectories 
  2. File extensions, matches files 
  3. Wildcard, matches directories and files

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.

File extension filters must start with a decimal point. Example: .obj File extension filter only matches files.

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
Example:  *foo*bar.*

The wildcard filter is compared  with 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
Pattern                   Test Against                             Results
--------------------      ----------------------------------       ----------
foo*                      foobarcar                                match
foo*                      carbarfoo                                no match
*foo                      carbarfoo                                match
*foo                      c:\alpha\beta\foo                        match
*foo\bin\*                foo\junk                                 no match
*foo\bin\*                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 rule can contain one or more filters separated by semicolons. Example: Connect*.xml;.obj;obj\

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.

Bookmarks

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

Keyboard

  • Control-A to select entire List
  • Space to toggle check boxes
  • Delete key to delete selected items or item under mouse
  • Up/Down to navigate up/down list and select row

Warning 

No undo to restore items removed from a list or any undo to restored DELETED files or directories. Deleted files and directories will not appear in your recycle bin so you have no way to undo your deletions.

Sample screen of File and Directory List Located using default filters:

Image 2

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 to folder menu
  4. Recursive pattern matcher
  5. Inline HTML help viewer

RegEdit, like most Windows applications, saves 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 of your entries.

C#
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");
}

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 the listview to the left. Here is the code I use to send keys to the UI in focus.

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

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

Example of Option menu showing register selection:

Image 3

Once VstudioCleaner is registered 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. Below is an image of the menu which appears when you right-click on a folder. This trick is thanks to "Leonardo Paneque" and his CodeProject "Solution Cleaner". Using trick #1 above, VStudioCleaner has menu picks to open the Windows Registry in both the section where VStudioCleaner stores its session info as well as the Shell Folder menu settings.

Sample of menu when you right-click a folder, showing VStudioCleaner:

Image 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.

C#
/// <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;
}

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 vstudtiocleaner a single program and did not want a CHM or HTML help file. Since my help text is reasonably short, I just embedded it in the program. Here is part of the code in helpdialog.cs.

C#
    public partial class HelpDialog : Form
    {
        public HelpDialog()
        {
            InitializeComponent();

            byte[] byteArray = Encoding.ASCII.GetBytes(helpHtml);
            MemoryStream mr = new MemoryStream(byteArray);
            this.webBrowser.DocumentStream = mr;
        }

        string helpHtml =
"<html>" +
"<body lang=EN-US>" +
"" +
"<p><span style='font-size:12.0pt'>Filters are patterns used to 
select directories and files.</span>" +
"<p>" +
"<b><span style='font-size:12.0pt'>Patterns fall into four categories:</span></b>" +
"" +
...
"</body>" +
"</html>";

Final Words

Additional source code and information is available on my home website:  

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

History

  • Aug 23, 2009 v1.4
    • Moved error messageBox from background files thread to main thread. Thanks to Ashutosh Bhawasinka.
  • Aug 30, 2009 v.5
    • Fixed sorting size column when search limit reached
    • Added inverse selection and delete Now menu choices
  • Sep 13, 2009 v1.6
    • Added support for multiple 'never' filter entries. 'Never' only needs to be a prefix to a filter name
    • Added warning message box to NOW delete menu pick
    • Another fix to sorting columns with missing values
    • Updated help message
    • Fixed filescan dialog optional filter box to keep selection active when you click on the list
  • Dec 17, 2011 v1.8
    • Added foreground and background colors to filters
    • Remember last bookmark and reset on startup. Show bookmark in title bar
    • Fixed registry settings and viewing on Windows 7
    • Fixed multiple path list, will color directory red if directory is invalid
    • Fixed some delete error status messages
    • Fixed links in About box, fixed about box to resize

License

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


Written By
Software Developer (Senior) IBM / WSI
United States United States
I love C/C++ for its speed and power and C#/Visual Studio for quick application development.

Unix/Linux is my favorite OS

Android Studio is the best IDE I have used.

Comments and Discussions

 
GeneralMy vote of 5 Pin
gvisol13-Aug-13 1:49
gvisol13-Aug-13 1:49 
QuestionHm... Pin
riskha11-Jan-12 2:33
riskha11-Jan-12 2:33 
AnswerWindows... not Pin
Dennis Lang15-Jan-12 2:47
Dennis Lang15-Jan-12 2:47 
QuestionWhy don't you delete to Recycle bin? Pin
Joe Sonderegger22-Dec-11 22:03
Joe Sonderegger22-Dec-11 22:03 
AnswerRe: Why don't you delete to Recycle bin? Pin
Dennis Lang23-Dec-11 7:36
Dennis Lang23-Dec-11 7:36 
SuggestionRe: Why don't you delete to Recycle bin? Pin
Joe Sonderegger2-Jan-12 22:10
Joe Sonderegger2-Jan-12 22:10 
QuestionUpdate v1.9 available at http://home.comcast.net/~lang.dennis/index.html Pin
Dennis Lang21-Dec-11 18:49
Dennis Lang21-Dec-11 18:49 
QuestionFix to Dec 17 update v1.8 Pin
Dennis Lang18-Dec-11 4:59
Dennis Lang18-Dec-11 4:59 
GeneralIssues Pin
Erich Ledesma30-Nov-10 1:48
Erich Ledesma30-Nov-10 1:48 
GeneralRe: Issues Pin
Dennis Lang21-Jun-11 9:24
Dennis Lang21-Jun-11 9:24 
QuestionGreat tool, but small bug? Pin
Neil Sutton11-Sep-09 4:14
Neil Sutton11-Sep-09 4:14 
AnswerRe: Great tool, but small bug? Pin
Dennis Lang11-Sep-09 9:07
Dennis Lang11-Sep-09 9:07 
GeneralRe: Great tool, but small bug? Pin
Dennis Lang13-Sep-09 7:18
Dennis Lang13-Sep-09 7:18 
GeneralGreat tool Pin
Saurabh.Garg1-Sep-09 4:35
Saurabh.Garg1-Sep-09 4:35 
GeneralCool program Pin
jesseseger1-Sep-09 4:13
professionaljesseseger1-Sep-09 4:13 
GeneralRe: Cool program Pin
Dennis Lang2-Sep-09 2:23
Dennis Lang2-Sep-09 2:23 
GeneralRe: Cool program Pin
jesseseger2-Sep-09 2:24
professionaljesseseger2-Sep-09 2:24 
GeneralThanks a lot [modified] Pin
Ashutosh Bhawasinka22-Aug-09 15:40
Ashutosh Bhawasinka22-Aug-09 15:40 
GeneralRe: Thanks a lot Pin
Dennis Lang23-Aug-09 5:31
Dennis Lang23-Aug-09 5:31 

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.