Question

I would like to use the Directory.GetDirectories method to get all directories with some exclusions. In particular I need to exclude directories that have a hyphen in them. I already found out regular expressions to not work as search patterns. What search pattern would I use?

Was it helpful?

Solution

Maybe a linq query would be sufficient?

    //query notation
    var result = from d in Directory.GetDirectories(path) 
                 where !d.Contains("-")
                 select d;
    //'dot' notation
    var result2 = Directory.GetDirectories(path)
                  .Where(dir => !dir.Contains("-"));

EDIT(More explanation)

The solution above is called "LINQ to Objects". It is a way of querying collections that implement IEnumerable or IEnumerable<T> interface. The GetDirectories method returns Array of string that is eligible to use Linq. There is a lot of stuff about Linq on the internet. To see te power of Linq flick through these examples on MSDN: 101 Linq Samples. BTW Linq is useful to retrieve data from various sources like XML, databases etx.

OTHER TIPS

System.Collections.ObjectModel.Collection<string> resultDirs=new System.Collections.ObjectModel.Collection<string> ();
            foreach (string  dir in System.IO.Directory.GetDirectories("path"))
            {
                if (!dir.Contains("-")) resultDirs.Add(dir);
            }

Not LINQ way:

    static void Main(string[] args)
    {

        string StartingPath = "c:\\";

        List<string> mydirs = new List<string>(); // will contains folders not containing "-"

        foreach (string d in Directory.GetDirectories(StartingPath))
        {                               
            if (!(d.Contains("_")))
            {
                mydirs.Add(d);
            }                

            foreach (string dir in mydirs)
            {
                Console.WriteLine(dir);
            }
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top