fraXis
fraXis

Reputation: 3221

How to get sub-directory names and files from a folder dragged and dropped onto an application

I have the following code, which will process the folder and files in that folder when a user drops it onto a button on my C# Winforms application window. This code works fine:

List<string> filepaths = new List<string>();

foreach (var s in (string[])e.Data.GetData(DataFormats.FileDrop, false))
   {
       if (Directory.Exists(s))
       {
           //Add files from folder
           filepaths.AddRange(Directory.GetFiles(s));
       }
       else
       {
           //Add filepath
           filepaths.Add(s);
       }
   }

However, if there is another folder inside of the main folder (sub-folder), it does not detect that sub-folder and list the files inside of the sub-folder.

Can someone please show me how to detect the name of the sub-folder and the files in the sub-folder as well?


Edit: Would something like this work?

string[] fileList = Directory.GetFiles(@s, "*.*", SearchOption.AllDirectories);

Upvotes: 1

Views: 5823

Answers (2)

Jmyster
Jmyster

Reputation: 995

Simalar to Frazell but I like to use file and directory info types like:

Edit: Added a ProcessFile() method

public void ProcessFolder(DirectoryInfo dirInfo)
{
    //Check for sub Directories
    foreach (DirectoryInfo di in dirInfo.GetDirectories())
    {
        //Call itself to process any sub directories
        ProcessFolder(di);
    }

    //Process Files in Directory
    foreach (FileInfo fi in dirInfo.GetFiles())
    {
        //Do something with the file here
        //or create a method like:
        ProcessFile(fi)
    }
} 

public void ProcessFile(FileInfo fi)
{
    //Do something with your file
    Debug.Print(fi.FullName);
    //...
}

Upvotes: 1

Frazell Thomas
Frazell Thomas

Reputation: 6111

You need to use Directory.GetDirectories() to pull back the subdirectories then loop through them similar to what you're already doing.

 // Process all files in the directory passed in, recurse on any directories  
    // that are found, and process the files they contain. 
    public static void ProcessDirectory(string targetDirectory) 
    {
        // Process the list of files found in the directory. 
        string [] fileEntries = Directory.GetFiles(targetDirectory);
        foreach(string fileName in fileEntries)
            ProcessFile(fileName);

        // Recurse into subdirectories of this directory. 
        string [] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
        foreach(string subdirectory in subdirectoryEntries)
            ProcessDirectory(subdirectory);
    }

Source: MSDN

Upvotes: 1

Related Questions