Search code examples
c#arrayslistboxenumerate

Extract a pattern from a group of filenames and place into listbox


I have a folder with a lot of files like this:

2016-01-02-03-abc.txt
2017-01-02-03-defjh.jpg
2018-05-04-03-hij.txt
2022-05-04-03-klmnop.jpg

I need to extract the pattern from each group of filenames. For example, I need the pattern 01-02-03 from the first two files placed in a list. I also need the pattern 05-04-03 placed in the same list. So, my list will look like this:

01-02-03
05-04-03

Here is what I have so far. I can successfully remove the characters but getting one instance of a pattern back into a list is beyond my pay grade:

        public void GetPatternsToList()
    {
        //Get all filenames with characters removed and place in listbox.

        List<string> files = new List<string>(Directory.EnumerateFiles(folderBrowserDialog1.SelectedPath));
        foreach (var file in files)
        {
            var removeallbeforefirstdash = file.Substring(file.IndexOf("-") + 1); // removes everthing before the dash in the filename
            var finalfile = removeallbeforefirstdash.Substring(0,removeallbeforefirstdash.LastIndexOf("-")); // removes everything after dash in name -- will crash if file without dash is in folder (not sure how to fix this either)

            string[] array = finalfile.ToArray(); // I need to do the above with each file in the list and then place it back in an array to display in a listbox
            List<string> filesList = array.ToList();
            listBox1.DataSource = filesList;
        }

    }

Solution

  • Try this:

    public void GetPatternsToList()
    {
        List<string> files = new List<string>(Directory.EnumerateFiles(folderBrowserDialog1.SelectedPath));
        List<string> resultFiles = new List<string>();
        foreach (var file in files)
        {
            var removeallbeforefirstdash = file.Substring(file.IndexOf("-") + 1); // removes everthing before the dash in the filename
            var finalfile = removeallbeforefirstdash.Substring(0, removeallbeforefirstdash.LastIndexOf("-")); // removes everything after dash in name -- will crash if file without dash is in folder (not sure how to fix this either)
            resultFiles.Add(finalfile);
        }
        listBox1.DataSource = resultFiles.Distinct().ToList();
    }