Jango
Jango

Reputation: 5545

How to count number of similar name files in one Folder in File System using c#?

To get the details of files, Directory.Getfiles("DirectoryPath", "*.zip") is returning me the all the files in a directory. Each file has a DateTime stamp in the Filename as a Postfix:

e.g. {87fbf03b-ec94-44a0-aac5-ffbaf6416700}_20100204_145154634008919142146021.zip

I am splitting out the GUID from the above file name.

string filName = Path.GetFileNameWithoutExtension(testFile).Split('_')[0];

This explanation is just to tell you guys that thats how I can have more than one file with the same name in the same directory.

Now my question is How can i get the results same like Group by query in T-SQL? I need to know how many times a similar file name is there in that directory.

Is it possible through linq? Yes then how?

Upvotes: 1

Views: 2566

Answers (3)

jason
jason

Reputation: 241701

Sure, use Enumerable.GroupBy:

var groups = from f in Directory.GetFiles("DirectoryPath", "*.zip")
             group f by f.Split('_')[0] into g
             select new {
                 GUID = g.Key
                 Count = g.Count()
             };
foreach(var group in groups) {
    Console.WriteLine("Guid = {0}: Count = {1}", group.GUID, group.Count);
}

It just reads so beautifully.

Since you specified in a comment that you can not use LINQ:

Dictionary<string, int> dict = new Dictionary<string, int>();
foreach(string filename in Directory.GetFiles("DirectoryPath", "*.zip")) {
    string guid = filename.Split('_')[0];
    if(!dict.ContainsKey(guid)) {
        dict.Add(guid, 0);
    }
    dict[guid]++;
}

foreach(KeyValuePair<string, int> kvp in dict) {
    Console.WriteLine("Guid = {0}: Count = {1}", kvp.Key, kvp.Value);
}

Upvotes: 2

62316e
62316e

Reputation: 225

Instead of string you should use Guid type.

var groups = from f in System.IO.Directory.GetFiles("DirectoryPath", "*.zip")
    group f by f.Split('_')[0] into g
    select new
    {
        GUID = new Guid(g.Key),
        Count = g.Count()
    };

Upvotes: 1

Marcel Gosselin
Marcel Gosselin

Reputation: 4716

Try this (not tested):

IList<string> fileNames = ...
var result = from fileName in fileNames
             group fileName by fileName.Split('_')[0] into grp
             select new
             {
                 FileName = grp.Key,
                 Count = grp.Count()
             };

Upvotes: 1

Related Questions