从所有硬盘中选择不同的文件类型扩展名?

时间:2009-10-21 17:42:00

标签: linq filesystems

有没有办法在我的系统中的所有驱动器上获取不同的文件扩展名列表?

2 个答案:

答案 0 :(得分:1)

嗯,是的,总有蛮力的做法。

    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);
            }
        }
    }

这将查找系统上具有任何给定扩展名的所有文件的计数(可供您访问)。

但是,如果您只想要一个文件类型列表,我建议您检查注册表的HKEY_CLASSES_ROOT部分。

无论如何,这是我的结果:

...

.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

答案 1 :(得分:1)

这样的事情应该有效:

var e = (from d in DriveInfo.GetDrives()
         from f in d.RootDirectory.GetFiles("*.*", SearchOption.AllDirectories)
         select f.Extension).Distinct();