0

I am trying to create a program that reads the folders inside the main directory and for each folder read each file (PDF) then move on to the next folder.

The code below is where i declare strings and start with a foreach statement.

string input_Path = @"C:\Users\username\Desktop\testinp\";
                string output_Path = @"C:\Users\username\Desktop\testinp\output\";
                string[] dirs = Directory.GetDirectories(input_Path, "*", SearchOption.TopDirectoryOnly);
                string[] files = Directory.GetFiles(input_Path, "*.pdf");

                foreach (string dir in dirs)
                {
                    string dirName = dir;
                }

Ocheezy
  • 113
  • 1
  • 11
  • 1
    Do you understand how to do nested loops? – NetMage Jan 16 '20 at 20:03
  • 1
    Does this answer your question? [Searching for file in directories recursively](https://stackoverflow.com/questions/9830069/searching-for-file-in-directories-recursively) – panoskarajohn Jan 16 '20 at 20:03
  • 1
    You don't even need to worry about loops on the folders if you just want all of the .pdf files at any depth: `string[] files = Directory.GetFiles(topLevelDir, "*.pdf", SearchOptions.AllDirectories);` – Romen Jan 16 '20 at 20:04
  • Yes I do, but I was trying to figure out what was the best way to go about writing them if that is the best way. – Ocheezy Jan 16 '20 at 20:05
  • @Romen For what I am doing it will select each folder, Optimized the PDF's and then once it finished the folder move it into another directory, then move on to the next folder. – Ocheezy Jan 16 '20 at 20:07
  • 2
    @O'Cheezy, And why does a flat list of all of the pdf files not work for that? You can use `Path.GetDirectoryName(file);` to get the specific subfolder from the full filepath. .NET has already implemented recursive file search in the functions that accept `SearchOptions.AllDirectories`, why re-implement it. – Romen Jan 16 '20 at 20:07
  • @O'Cheezy, They wouldn't be split up or moved all at once unless you intentionally wrote the code that way. Take a look at the strings returned from `Directory.GetFiles()` using the `SearchOptions` overload, you'll have everything you need to determine which subdirectories the files belong to and process them accordingly. – Romen Jan 16 '20 at 20:11
  • @Romen I guess I didn't think about it like that. That pretty much answers my question, and panoskarajohn 's link made me understand what you were saying. A big thanks to both of you! – Ocheezy Jan 16 '20 at 20:16

1 Answers1

0

Here is a complete explanation of how to do it along with code examples. https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-iterate-through-a-directory-tree

xsoftie
  • 116
  • 2
  • 10