Question

I'm trying to construct a parallel query using LINQ to get all of the text files and one CSV file in a certain directory and its subdirectories. I want to exclude hidden, temporary, and system files from even being considered by the query in hopes of speeding it up. (The directory is huge.) While I'm at it I also want to exclude a couple of the subdirectories. Here's my code:

ParallelQuery<string> getFiles =
    Directory.EnumerateFiles(@"C:\", "*", SearchOption.AllDirectories)
    .AsParallel().Where(f => (
        FileAttributes.Hidden == 0 &&
        FileAttributes.System == 0 &&
        FileAttributes.Temporary == 0 &&
        !Path.GetDirectoryName(f).Contains("TempDir") &&
        !Path.GetDirectoryName(f).Contains("OtherDir") &&
        (Path.GetExtension(f).ToUpper() == ".TXT" ||
        Path.GetFileName(f) == "GoodFile.csv")));

I tried to use the accepted answer to this question as a starting point. In Visual Studio (2013 Express Desktop, if it matters) I'm getting a green underline on the 7th-9th lines, the ones excluding certan subdirectories and restricting the results to .txt files, telling me Unreachable expression code detected. However, the line that includes the .csv file seems to been fine. Executing the query returns no results and does not throw any exceptions.

I'm still very, very new to LINQ so please forgive me if the issue here is blatantly obvious. Can anybody shed some light on this? Or perhaps there is a much better way of going about this?

Was it helpful?

Solution

FileAttributes.Hidden == 0 &&
FileAttributes.System == 0 &&
FileAttributes.Temporary == 0 &&

This is testing that the enumeration values are == 0, not if a file has that attribute. You need to create instances of System.IO.FileInfo to use FileInfo.Attributes. You can use .Select(f => new System.IO.FileInfo(f)) for this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top