Home > Net >  Count how many files starts with the same first characters c#
Count how many files starts with the same first characters c#

Time:04-12

I want to make function that will count how many files in selected folder starts with the same 10 characters.

For example in folder will be files named File1, File2, File3 and int count will give 1 because all 3 files starts with the same characters "File", if in folder will be

File1,File2,File3,Docs1,Docs2,pdfs1,pdfs2,pdfs3,pdfs4 

will give 3, because there are 3 unique values for fileName.Substring(0, 4).

I've tried something like this, but it gives overall number of files in folder.

int count = 0;

foreach (string file in Directory.GetFiles(folderLocation))
{
    string fileName = Path.GetFileName(file);

    if (fileName.Substring(0, 10) == fileName.Substring(0, 10))
    {
        count  ;
    }
}

Any idea how to count this?

CodePudding user response:

You can try quering directory with a help of Linq:

using System.IO;
using System.Linq;

...

int n = 10;

int count = Directory
  .EnumerateFiles(folderLocation, "*.*")
  .Select(file => Path.GetFileNameWithoutExtension(file))
  .Select(file => file.Length > n ? file.Substring(0, n) : file)
  .GroupBy(name => name, StringComparer.OrdinalIgnoreCase)
  .OrderByDescending(group => group.Count())
  .FirstOrDefault()
 ?.Count() ?? 0;

CodePudding user response:

You could instantiate a list of strings of files with a unique name, and check if each file is in that list or not:

int count = 0;
int length = 0;
List<string> list = new List<string>();
foreach (string file in Directory.GetFiles(folderLocation))
{
    boolean inKnown = false;
    string fileName = Path.GetFileName(file);
    for (string s in list)
    {
        if (s.Length() < length)
        {
            // Add to known list just so that we don't check for this string later
            inKnown = true;
            count--;
            break;
        }
        if (s.Substring(0, length) == fileName.Substring(0, length))
        {
            inKnown = true;
            break;
        }
    }
    if (!inKnown)
    {
        count  ;
        list.Add(s);
    }
}

The limitation here is that you are asking if the first ten characters are the same, but your examples given showed the first 4, so just adjust the length variable according to how many characters you would like to check for.

CodePudding user response:

@acornTime give me idea, his solution didn't work but this worked. Thanks for help!

List<string> list = new List<string>();
        foreach (string file in Directory.GetFiles(folderLocation))
        {
            string fileName = Path.GetFileName(file);
            list.Add(fileName.Substring(0, 10));
        }
        list = list.Distinct().ToList();
        //count how many items are in list
        int count = list.Count;
  • Related