0

When running the following code:

var files = dir.EnumerateFiles("*.*", SearchOption.AllDirectories).Where(f => ext.Contains(Path.GetExtension(f.FullName))) foreach (FileInfo file in files) { file.CopyTo(destPath, true); } 

Where dir is a DirectoryInfo
Where ext is a List of strings containing accepted file extensions

Upon getting to the foreach loop, files is null.
Inside the foreach (at the in statement), the program jumps back to the => statement then fills files. When it's done, it skips over the foreach loop and never enters it.

I am lost here. Why is my code jumping one line back? I tried Enumerate and GetFiles, none seem to work.

2
  • Maybe the extensions need a dot in the ext list Commented Jun 22, 2017 at 20:08
  • That also worked. Thanks for the help. Commented Jun 22, 2017 at 20:46

1 Answer 1

1

The reason for the code "jumping back" is something called Deferred Execution. The LINQ expression you have there is not actually executed until the results are used in the foreach loop.

As for skipping over the foreach loop - that happens because the enumeration is empty. As @Slai mentioned in a comment, there might be a problem with your extension list (forgetting the '.' before the extension name is a common mistake).

If you want the enumeration to execute immediately instead of being deferred (makes debugging easier) the easiest way is just to end your LINQ expression with a .ToList() like so:

var files = dir.EnumerateFiles("*.*", SearchOption.AllDirectories) .Where(f => ext.Contains(Path.GetExtension(f.FullName))) .ToList(); 
Sign up to request clarification or add additional context in comments.

1 Comment

I'm gonna have to read up on that Deferred Execution. That definitely fixed it. Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.