My application is C# 3.5 runs on Windows 7 Ultimate, 64 bit. It goes through all folder subfolders to perform its job. However, it fails (falls into the infinite loop until StackOverflow.com exception) if run against the folder which name is only one symbol which is #255.
To reproduce, you can do the following:
- run Windows Explorer create C:\Temp folder in this folder
- create new folder and rename it with Alt-255 (using numeric keypad)
- create subfolders “first” and “second” there
- create subfolders “1” and “2” under Temp
So you now have:
- C:\1
- C:\2
- C:\ \first
- C:\ \second
For such C:\Temp folder with a subfolder with the name #255 (or more #255 symbols) the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
class Program
{
public static string[] GetDirectories(string pathToTraverse)
{
List<string> result = new List<string>();
foreach (DirectoryInfo subFolder in new DirectoryInfo(pathToTraverse).GetDirectories())
{
result.Add(subFolder.FullName);
}
return result.ToArray();
}
public static void TraverseFolders(string folderToTraverse)
{
foreach (string subFolder in GetDirectories(folderToTraverse))
{
Console.WriteLine(subFolder);
TraverseFolders(subFolder);
}
}
static void Main(string[] args)
{
TraverseFolders(@"C:\Temp");
}
}
will never end and will give you result like:
C:\Temp\
C:\Temp\1
C:\Temp\2
C:\Temp\
C:\Temp\1
C:\Temp\2
C:\Temp\
C:\Temp\1
C:\Temp\2
C:\Temp\
So how do I correctly enumerate such folder subfolders?
The following program runs perfectly and does not result in a stack overflow error.
It produces the following output:
The penultimate apparently blank line is in fact the directory named Alt+255.
Consequently I believe that your problem is not related to the code you have shown and is in fact elsewhere in some code that you have not presented to us.
I’m running on Windows 7 with VS 2010 Express targeting .net 3.5.
Now that your update shows all your code, I can see what is happening. The .net code is presumably trimming the directories and so the folders with white space get lost.
So
@"C:\Temp\ "is trimmed to@"C:\Temp\".I found the following trivial modification avoided the infinite loop:
Adding a trailing path separator stops the trimming that appears to occur in the call to DirectoryInfo. In the example above this means that
@"C:\Temp\ \"is passed to DirectoryInfo which yields the expected results.I guess you should probably use a routine that only adds a trailing path separator if one is not already present. And you may want to avoid hardcoding the @”\” as path separator, but that’s for you to work out now that you know what the underlying cause of your problem is.