Directory.GetFiles: Show only files starting with a numeric value

ぃ、小莉子 提交于 2019-12-01 16:49:21

问题


How can i get the Directory.GetFiles to only show me files starting with a numeric value (eg. 1abc.pdf);

Directory.GetFiles(@"C:/mydir", "0-9*.pdf")

回答1:


To get files that start with any numeric value, regardless of the number of digits, you could use a regular expression:

var files = Directory.GetFiles(@"c:\mydir", "*.pdf")
                     .Where(file => Regex.IsMatch(Path.GetFileName(file), "^[0-9]+"));
                     //.ToArray() <-add if you want a string array instead of IEnumerable



回答2:


There is no way to specify this directly in the search pattern. It's capabilities are pretty limited (mainly supports the * wildcard). The best way to accomplish this is to filter on *.pdf and then use a LINQ query to filter to the ones that start with a digit

Directory
  .GetFiles(@"c:\mydir", "*.pdf")
  .Where(x => Char.IsDigit(Path.GetFileName(x)[0]));


来源:https://stackoverflow.com/questions/9653201/directory-getfiles-show-only-files-starting-with-a-numeric-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!