Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

A simple desktop sorter!

4.00/5 (1 vote)
25 Apr 2013CPOL4 min read 9.1K   98  
How to sort your desktop, the easy way!

Quick note for people who are not sure on how to use the file added to the article:

Download Winrar from http://www.rarlab.com  

Introduction 

I used to have a desktop full of icons, and sometimes the amount was so huge that I had no idea on how to get rid all of them. Then I became too lazy at one point to sort them out, and see what I needed and what I did not. So, at one morning I decided to spend <15 minutes on this little program that sorts them for you. There is no difficult code in this as the computer sorts all of it out in probably less then three seconds (no joking!).

Background 

So, why is this program useful, and what exactly does it do, and is it safe?

Well, first of all this program will be useful to people with a bit of knowledge on files in general. The program sorts every file (directories can be added but I do not see why) in a sub-folder based on its extension. This is done via I believe its called a "Mime" I do not have an exact clue on what it is, but it helped me a lot on sorting the files in general.

I was going to make three different parts on the questions but I think I already explained what it does and why it is useful, so is it safe? This is a good question, and it actually is safe, before the file gets moved and does anything to your computer it will make sure the file is not in use with another program, or it actually is able to being moved to a folder. So, exceptions of any kind would not occur as far as I am concerned.

Using the code

Now, the code is important but what is more important is the logic behind it. The logic in this code is simply this:

  1.  Get every file on the desktop.
  2.  Make sure the file is not locked (or in-use).
  3.  Create the directory for the file if it doesn't exist yet.
  4.  Move the file. 

If you understand that logic, then the code would not be as difficult as it seems. Here is the void that will sort all the files. There will be comments in the code to explain what it does, how it does it.

C#
public static void CleanDesktop()
{
    // -- Notify the console.
    Console.WriteLine("Retrieving desktop files.");

    // -- Get the files on the desktop.
    string[] Files = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.Desktop));

    // -- Prepare a file info.
    FileInfo Info;

    if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Files\\"))
        Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Files\\");


    // -- Run through the files.
    foreach (string f in Files)
    {
        // -- Get the file info.
        Info = new FileInfo(f);

        // -- Notify the console.
        Console.WriteLine("Sorting file  " + Info.Name + ".");

        // -- Check if the file is in use or not.
        if (IsFileLocked(Info))
        {
            Console.WriteLine(Info.Name + " is in use; Not sorting.");
        }
        else
        {
            // -- Notify the console.
            Console.WriteLine("Sorting " + Info.Name + " to " + 
              (Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + 
              "\\Files\\" + GetMimeType(Info.FullName)));

            // -- Move the file, and created the folder if it doesn't exist.
            if (Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + 
                 "\\Files\\" + GetMimeType(Info.FullName)))
            {
                // -- Notify the console.
                Console.WriteLine("The folder exists moving " + Info.Name);
                Info.MoveTo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + 
                             "\\Files\\" + GetMimeType(Info.FullName), Info.Name));
            }
            else
            {
                // -- Notify the console.
                Console.WriteLine("The folder doesn't exists creating the folder and then moving " + Info.Name);
                Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + 
                              "\\Files\\" + GetMimeType(Info.FullName));
                Info.MoveTo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + 
                              "\\Files\\" + GetMimeType(Info.FullName), Info.Name));
            }
        }
    }
}

As I stated before, this is the only void you have to run in order to sort your desktop. However, there are as you can probably tell two other voids going on. One of them is to check if a file is locked or not, this is done by attempting to read/write from the file and check if any exceptions occur. Here is how to do that:

C#
public static bool IsFileLocked(FileInfo file)
{
    FileStream stream = null;

    try
    {
        stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    }
    catch (IOException)
    {
        // -- We are unable to read or write from the file; It is in use.
        return true;
    }
    finally
    {
        if (stream != null)
            stream.Close();
    }

    // -- The file is not locked since it has not returned yet. 
    return false;
} 

If you feel like this is hard to understand, I can tell you a few things about it, it actually is pretty simple, let me explain it in simple steps if you wish to understand it; 

  1. Create a Filestream (a stream is an open bridge between two things, in this case, a file and our program) to the specific FileInfo (which is a class that holds information on a file).
  2. Attempt to open the stream with Reading and Writing access.
  3. If this attempt fails and there occurs an error return true, as in, the file is locked.
  4. Finally, after we have attempted opening it we make sure to close the stream if it is not null. Otherwise your program would be using the file.
  5. Well, so it seems that the file is not locked as it has not returned a boolean yet, so we return it as true.

The last void is a bit harder, and for me really hard, as I have never worked with registry I have about zero clue on what this actually does. Well, I could use some common sense in it and tell that it is attempting to get the RegistryValue for the given filename. So, last but not least, here is the MimeVoid:

C#
public static string GetMimeType(string fileName)
{
    string mimeType = "application/unknown";
    string ext = System.IO.Path.GetExtension(fileName).ToLower();
    Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
    if (regKey != null && regKey.GetValue("Content Type") != null)
        mimeType = regKey.GetValue("Content Type").ToString();
    return mimeType;
}

Points of Interest  

I have learned a lot of nice things about this concept, for one, it is really fast, and not a lot of work to make. Also, I will use this for personal use whenever I get stuck with a messy background.

History

Created the article. 

Additional message

I do apologize if my English is not the best. I am not English myself but do like the language and I will try and keep the article updated regularly for any problems in it.

License

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