2
bool match = Regex.IsMatch(Path.GetFileName(Directory.GetFiles(string.Format(@"C:\apps\{0}\", app), "*.config").ToString()).ToLower(), "loggingconfiguration.config");

I have been using the code below to place the configs into a list and then looping through each of them to see if they match the filename of "loggingconfiguration.config" or "*app*.config." This works without a problem, but I am not sure if this is the best way to handle the scenario.

List<string> configFiles = Directory.GetFiles(string.Format(@"C:\apps\{0}\", app), "*.config").ToList<string>();

foreach (var item in configFiles)
{
    if (item.ToLower().Contains("loggingconfiguration.config") || (Path.GetFileName(item.ToLower()).Contains(app)))
    {
        //Do something
    }
}

I wanted to know if there is a way to cut out the step of looping through the list by searching for the "loggingconfiguration.config" or "\*app*.config" first. My attempt at the top results in system.string[] for the `Path.GetFileName(Directory.GetFiles(string.Format(@"C:\apps{0}\", app), "*.config") search.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
Pam
  • 63
  • 5

2 Answers2

1

You can use LINQ to build a query which returns an IEnumerable and then iterate over it.

var configFiles = Directory.GetFiles(string.Format(@"C:\apps\{0}\", app), "*.config")
    .Where(p => p.ToLower().Contains("loggingconfiguration.config") || Path.GetFileName(p.ToLower()).Contains(app));

foreach (string s in configFiles)
{ 
    //dowork
}

This hides some of the filtering details from your source code, but is not necessarily more performant.

Michael
  • 1,803
  • 1
  • 17
  • 26
1

Assuming you're using .NET 4 or above you can do:

var files = new DirectoryInfo(string.Format(@"C:\apps\{0}\", app))
    .EnumerateFiles("*.config")
    .Where(x=>
        x.Name.Equals("loggingconfiguration.config", StringComparison.OrdinalIgnoreCase) ||
        x.Name.ToUpperInvariant().Contains("APP"));

Otherwise use GetFiles:

var files = new DirectoryInfo(string.Format(@"C:\apps\{0}\", app))
    .GetFiles("*.config")
    .Where(x=>
        x.Name.Equals("loggingconfiguration.config", StringComparison.OrdinalIgnoreCase) ||
        x.Name.ToUpperInvariant().Contains("APP"));

EnumerateFiles info there

Alessandro D'Andria
  • 8,663
  • 2
  • 36
  • 32
  • I ended up using a slight variation of the first query to retrieve the config file names. – Pam Oct 22 '13 at 16:18