【发布时间】:2018-12-07 20:38:48
【问题描述】:
我有一个文件夹,里面有很多这样的文件:
2016-01-02-03-abc.txt
2017-01-02-03-defjh.jpg
2018-05-04-03-hij.txt
2022-05-04-03-klmnop.jpg
我需要从每组文件名中提取模式。 例如,我需要放在列表中的前两个文件中的模式 01-02-03。我还需要将模式 05-04-03 放在同一个列表中。因此,我的列表将如下所示:
01-02-03
05-04-03
这是我目前所拥有的。我可以成功删除字符,但将一个模式实例重新添加到列表中超出了我的工资等级:
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;
}
}
【问题讨论】:
标签: c# arrays listbox enumerate