c# Cannot get list of subdirectories

2019-08-31 23:49发布

问题:

I've seen this code (and similar) all over the web, but I just cannot get it to work. Whenever I debug it line by line, it breaks out of debugging and loads the application. No error messages are presented, and any code after the "faulty" line remains unprocessed.

Here is the offending code:

foreach (string folder in allFolders)
{
    string[] subFolders = Directory.GetDirectories(folder, 
        "*", SearchOption.AllDirectories);
    MessageBox.Show("Test");
}

The foreach loop is entered into, but the message box is never displayed.

If I remove the SearchOption.AllDirectories the code is processed successfully, but I need some way to include all subdirectories within the directories.

Any ideas?

回答1:

Your code works fine for me.
It seems to me that this method call just takes a lot of time to execute. For example, if there is a root directory in allFolders you have to wait several minutes (depends on your system parameters). Have you checked this code snippet on directories with just a few number of nested directories?
I assumed, that you work in winforms and execution just doesn't reach MessageBox.Show call.



回答2:

MessageBox.Show is not working because your code is under web environment, while MessageBox is used in winform. Usually we use javascript to pop up a message box e.g. alert('hi').



回答3:

Tested your code and it's working OK, so the problem may be in another place of the code, or it may be a permission issue, although it returns an exception when it happens, the MSGBOX shows OK too.

        List<string> allFolders = new List<string>();
        allFolders.Add(@"C:\joomla\");

        foreach (string folder in allFolders)
        {
            string[] subFolders = Directory.GetDirectories(folder, "*", SearchOption.AllDirectories);
            MessageBox.Show("Test");
        }