views:

108

answers:

2

Is there some way to get a distinct list of file extensions on all drives in my system?

+1  A: 

Well, yes, there is always the brute-force approach.

    static void Main(string[] args)
    {
        Dictionary<string, int> Extenstions = new Dictionary<string, int>();

        PopulateExtenstions("C:\\", Extenstions);

        foreach (string key in Extenstions.Keys)
        {
            Console.Write("{0}\t{1}", key, Extenstions[key]);
        }
        Console.ReadKey(true);
    }

    private static void PopulateExtenstions(string path, Dictionary<string, int> extenstions)
    {
        string[] files = null;
        string[] subdirs = null;

        try
        {
            files = Directory.GetFiles(path);
        }
        catch (UnauthorizedAccessException)
        {
        }

        try
        {
            subdirs = Directory.GetDirectories(path);
        }
        catch (UnauthorizedAccessException)
        {
        }

        if (files != null)
        {
            foreach (string file in files)
            {
                var fi = new FileInfo(file);

                if (extenstions.ContainsKey(fi.Extension))
                {
                    extenstions[fi.Extension]++;
                }
                else
                {
                    extenstions[fi.Extension] = 1;
                }
            }
        }
        if (subdirs != null)
        {
            foreach (string sub in subdirs)
            {
                PopulateExtenstions(sub, extenstions);
            }
        }
    }

This will find the count of all files with any given extension on your system (that is accessable to you).

However, I would suggest if you just want a list of filetypes, to check the HKEY_CLASSES_ROOT section of your registry.

Anyways, here is my result:

...

.tga    1453
.inf    1491
.mum    1519
.cs     1521
.sys    1523
.gif    1615
.vdf    1615
.txt    1706
.h      1775
.DLL    1954
.bmp    2522
.xml    2540
.exe    2832
        3115
.png    3128
.jpg    3385
.GPD    3629
.cat    3979
.vcd    5140
.mui    6153
.wav    8522
.dll    14669
.manifest       19344
Elapsed Time: 17561
John Gietzen
+1  A: 

Something like this should work:

var e = (from d in DriveInfo.GetDrives()
         from f in d.RootDirectory.GetFiles("*.*", SearchOption.AllDirectories)
         select f.Extension).Distinct();
Greg Beech
This throws an exception for me. UnauthorizedAccessException.
John Gietzen
Technically that is correct; it's telling you that you do not have sufficient permission to find out the answer to your question. If what you mean is "I want to get a distinct list of file extensions **for files that I have access to** on all drives in my system" then you can use John's longer answer which discards unauthorized access exceptions.
Greg Beech
Wow, that's tight syntax, thanks!
tbone
But ya, i guess if it causes an exception....or could it be split up a bit to put a try catch in?
tbone