Question

I am using this code:

  var list = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, _globalSetting.CompanyCode + "trn*.???", SearchOption.TopDirectoryOnly).ToList();

  foreach (var listitem in list)
  {
    listBox_Files.Items.Add(Path.GetFileName(listitem));
  }

but it's giving me more than I need. I'd like it to only give me files with 3 extensions, and if I could, only those with numbers in them. I tried the ??? above but it's giving me this:

WEBTRN25.000
WEBTRN25.001
WEBTRN25.000_copy
WEBTRN34.ABC

I also tried ### but that gave me no results.

This is what I would like it to give back:

WEBTRN25.000
WEBTRN25.001

Any suggestions?

Était-ce utile?

La solution

You could combine a Regex expression with a Linq clause Where

Regex r = new Regex(@"^\.\d\d\d$");
var list = Directory.EnumerateFiles(AppDomain.CurrentDomain.BaseDirectory, 
                               _globalSetting.CompanyCode + "trn*.*", 
                               SearchOption.TopDirectoryOnly)
                               .Where(x => r.IsMatch(Path.GetExtension(x)));

Notice that I have replaced your call to GetFiles with EnumerateFiles. This method allows to start the enumeration of the collection before the whole directory list has been read. So, EnumerateFiles (if you have many files in the directory) could be more efficient.

Autres conseils

you could use a regex to make sure the file name ends in [dot then three numbers]

.*\\.[0-9]{3}$

or something like that

Try using LINQ:

var list = Directory.GetFiles("<DIRECTORY>").Where(a=> Regex.IsMatch(a, @"\d\d\d")).ToList().Foreach((b)=> Path.GetFileName(b));. You wouldnt need the foreach loop

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top