Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting Files Extensions C#

Tags:

c#

directory

Hi i'm a c# begginer and i'd like to do a simple program which is going to go through a folder and count how many files are .mp3 files and how many are .flac .

Like I said the program is very basic. It will ask for the music folder path and will then go through it. I know there will be a lot of subfolders in that main music folder so it will have to open them one at the time and go through them too.

E.g

C:/Music/ will be the given directory. But it doesn't contain any music in itself. To get to the music files the program would have to open subfolders like

C:/Music/Electronic/deadmau5/RandomAlbumTitle/ Only then he can count the .mp3 files and .flac files and store them in two separated counters. The program will have to do that for at least 2000 folders.

Do you know a good way or method to go through files and return its name (and extension)?

like image 841
phadaphunk Avatar asked Feb 26 '12 18:02

phadaphunk


People also ask

How do I count the number of files?

Open Windows Explorer. Browse to the folder containing the files you want to count. As shown in the picture below, in the right details pane, Windows displays how many items (files and folders) are in the current directory. If this pane is not shown, click View and then Details pane.

How do I count files in CMD?

How to count the files in a folder, using Command Prompt (cmd) You can also use the Command Prompt. To count the folders and files in a folder, open the Command Prompt and run the following command: dir /a:-d /s /b "Folder Path" | find /c ":".

Is there a way to count the number of files in a folder?

Right-click on the folder and select the “Properties” option. The “Properties” window will open and you will be able to see the number of files and subdirectories located in the directory selected.


2 Answers

You can use System.IO.DirectoryInfo. DirectoryInfo provides a GetFiles method, which also has a recursive option, so if you're not worried about speed, you can do this:

DirectoryInfo di = new DirectoryInfo(@"C:\Music");

int numMP3 = di.GetFiles("*.mp3", SearchOption.AllDirectories).Length;
int numFLAC = di.GetFiles("*.flac", SearchOption.AllDirectories).Length;
like image 150
Ry- Avatar answered Oct 03 '22 10:10

Ry-


Use DirectoryInfo and a grouping by the file extension:

var di = new DirectoryInfo(@"C:/Music/");
var extensionCounts = di.EnumerateFiles("*.*", SearchOption.AllDirectories)
                        .GroupBy(x => x.Extension)
                        .Select(g => new { Extension = g.Key, Count = g.Count() })
                        .ToList();

foreach (var group in extensionCounts)
{
    Console.WriteLine("There are {0} files with extension {1}", group.Count, 
                                                                group.Extension);
}
like image 44
BrokenGlass Avatar answered Oct 03 '22 10:10

BrokenGlass