title: Exclude directories that contain sub directories?
body: <p>I have the following code:</p>
  
  <pre><code>var directories =  Directory.GetDirectories(
          environmentSettings.SourcePath, 
          "*",
          SearchOption.AllDirectories)
      .Where(dir =&gt; !environmentSettings.FolderExclusions
                                        .Contains(Path.GetFileName(dir)));
  </code></pre>
  
  <p>I want to create a directory in the target path except for ones that show up in the exclusion list. This works, but only if the directory is directly under the root and does not contain sub-directories.</p>
  
  <p>As an example, if the exclusion list contains a directory called <code>Custom</code> and the root directory is <code>C:\App</code>, it will exclude <code>C:\App\Custom</code> and not create it in the target path, but as soon as it encounters something like <code>C:\App\Custom\Sub</code>, it will end up creating this on the target path.</p>
  
  <p>Can't get it to work for File:</p>
  
  <p>//Copy all the files</p>
  
  <pre><code>var files = Directory.GetFiles(environmentSettings.SourcePath, "*", SearchOption.AllDirectories)
        .Select(file =&gt; new FileInfo(file))
        .Where(file =&gt; !environmentSettings.FolderExclusions
                                           .Contains(file.Name) &amp;&amp; 
                       !environmentSettings.FolderExclusions
                                           .Contains(file.Directory.Name));
  </code></pre>
  
  <p>The problem above, is that I don't know how to tell how nested the file is, for example, if it is under <code>c:\App\Custom\thumbs.db</code>, it works fine, I think, but if it is under <code>c:\App\Custom\sub1\sub2\thumbs.db</code>, it still copies the file and the Custom directory which is what I don't want.  I basically need to get the directory right below <code>c:\App</code> and if that is <code>Custom</code>, then I exclude the file.</p>
  
  <pre><code>var files = Directory.GetFiles(environmentSettings.SourcePath, "*", SearchOption.AllDirectories)
              .Select(file =&gt; new FileInfo(file))
              .Where(file =&gt; !environmentSettings.FolderExclusions.Contains(file.Directory.Name) &amp;&amp; (file.Directory.Parent == null || !environmentSettings.FolderExclusions.Contains(file.Directory.Parent.Name)));
  </code></pre>
  
  <p>When I run the following code to loop through all my files and put them in a target directory, I run into a Directory not found exception:</p>
  
  <pre><code>//Copy all the files
  foreach (var file in files)
  {
  File.Copy(file.Name, file.FullName.Replace(environmentSettings.SourcePath, environmentSettings.TargetPath));
  }
  </code></pre>
  
  <p>The problem is that the source file maybe something like \network\app1\one.mp3 and my target directory might be c:\programdata\myapp.  It is saying it can't find <code>one.mp3</code> when copying the files from the source.  Not sure how to handle this.</p>