Creating (N) directories in a specific path in a loop stopping abruptly

c# loop through files in folder and subfolders
c# directory getfiles loop
get all files in directory and subdirectories c
c# get all subdirectories recursively
c# loop files in a directory
c# for each file in directory
c# search files in directory and subdirectories
how to get folder details in c#

I am attempting to create 10,000 folders in a specific directory. I have an algorithm for creating a random names for each folder.

The issue I am having is when I run this code, It stops with creating about 21 directories. The MessageBox.Show() is debug, however, it never pops up.

this.WorkingDir is a string property that looks like this.

"C:\\Users\\Reapism\\Desktop\\Yo\\"

        DirectoryInfo directoryInfo;
        string dirName; // directory name
        const int dirNameLength = 15;

        for (int i = 0; i < 10000; i++) {
            dirName = GetRandomString(dirNameLength); // generates "unique name"
            try {
                directoryInfo = Directory.CreateDirectory(this.WorkingDir + dirName);
            } catch (Exception e) {
                MessageBox.Show($"{i} {dirName} failed. {e.ToString()}");
            }
        }

        // Inserting a breakpoint here yields 21 directories

        DirectoryInfo d = new DirectoryInfo(this.WorkingDir);
        DirectoryInfo[] directories = d.GetDirectories($"*");

        foreach (DirectoryInfo dir in directories) {
            try {
                Directory.Delete(dir.FullName);
            } catch (Exception e) {
                throw new FileNotFoundException($"Error deleting the directory!" + e.ToString());
            }
        }

The interesting thing is when I use the Debugger, and step through each iteration of the for loop in creating the directories, it goes further than 21 directories, and likely goes all the way to 10k. This would lead me to believe there is a limit to creating directories in a certain number of time.

Whats troubling is that no exception is thrown, the loop just discontinues.

Does this have to do with the CPU working quicker than the Disk can report or write a new Folder? If so, how can I get around this? This function is a timed function and using a Thread.Sleep(50) for example cannot be used.

Your function GetRandomString generates non unique names, because you create new Random every times. You can use private class member Random which been created one times with class instance. I wrote sample counting unique names.

string[] dirNames = new string[10000];

for (i = 0; i < 10000; ++i)
    dirNames[i] = GetRandomString(dirNameLength); // generates "unique name";

foreach (var dr in dirNames.GroupBy(x => x).Select(x => new { Name = x.Key, Count = x.Count() }).Where(x => x.Count > 1))
{
    Console.WriteLine($"{dr.Count} {dr.Name}");
}

Try this. Аnd don't forget that filenames are case insensitive, so you should use only 36 characters, not 62.

private static readonly char[] charList = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".ToCharArray();
private static readonly Random _random = new Random();

private static string GetRandomString(int length)
{
    if (length < 1)
        throw new ArgumentOutOfRangeException("Length must be greater than 0!");

    return new string(Enumerable.Repeat(charList, length).Select(s => s[_random.Next(s.Length)]).ToArray());
}

How to iterate through a directory tree, The phrase "iterate a directory tree" means to access each file in each nested subdirectory under a specified root folder, to any depth. This behavior guards against the risk of entering into an infinite loop when two reparse You can then use this string to create a new FileInfo or DirectoryInfo object as� 1 Creating (N) directories in a specific path in a loop stopping abruptly Mar 25 '19 1 'Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' threw an exception.' Apr 8

Probably your function GetRandomString throws an exception when executes real-time. Put it into try block and check. I tryed to create 10000 folders with names 1,2,3 ...10000 and I have created all.

    for (int i = 0; i < 10000; ++i)
    {
        Directory.CreateDirectory(Path.Combine(WorkingDir, $"{i}"));
    }

Python Write to File – Open, Read, Append, and Other File Handling , Working with files is an important skill that every Python developer But if the file is within a nested folder, like this: use a specific path to tell the function that the file is within another folder. With this mode, you can create a file and then write to it dynamically Let's break this error down this line by line:. If you have to handle these exceptions on specific subfolders, you must manually walk the directory tree, as shown in the following examples. When you manually walk a directory tree, you can handle the subdirectories first (pre-order traversal), or the files first (post-order traversal). If you perform a pre-order traversal, you walk the whole

Regarding the update for GetRandomString()...

When you create a new instance of Random without passing it a seed, the default constructor will seed the new instance from Environment.TickCount - the time in milliseconds since the computer was started. Since this has a resolution of 1ms your code is most likely creating a lot of Random instances with the same seed value. This means that the method will return the same values every time until Environment.TickCount rolls over to the next value.

To solve this you should use a single Random instance and use that in all of the calls. Something like this should work:

private Random _rnd = null;

private string GetRandomString(int length) 
{
    if (_rnd == null)
        _rnd = new Random();

    if (length < 1) 
        throw new ArgumentOutOfRangeException("Length must be greater than 0!");

    var sb = new StringBuilder(length);
    for (int i = 0; i < length; i++)
        sb.Append(charList[_rnd.Next(charList.Length)]);
    return sb.ToString();
}

It does essentially the same as what you already have, but only creates a single Random instance. And avoids all that nasty string composition you have going on, so it'll be a tiny bit faster and more memory-friendly.

Another method, if you don't care about the actual names, would be to use Guid.NewGuid() to create guaranteed-unique values.

Writing shell scripts, Errors are not the only way that a script can terminate unexpectedly. #!/bin/ bash echo "this script will endlessly loop until you stop it" while true; do : # Do This script processes a text file specified on the command line with the pr It is a Unix tradition to use a directory called /tmp to place temporary files used by programs. Please note that you can't create files under non-existent directories using 'touch' command. You should first create the directories and then create files. As you can see in the above examples, creating multiple files and directories isn't that difficult. We can do it with some one-liner commands as described above.

[PDF] IDL for Astronomers - UGAstro, This acts as a preventative measure to stop you making the mistake of removing ”List”; Lists all items in either the working directory or specified path. 5. cd: ” Change used command is kill which abruptly ends any process. For instance say we IDL we want the loop to stop when i=4, and then the loop starts. Next our� Keep in mind that the mkdir() method cannot create sub-directories on a deeper level than one in a single call. To create an entire path you have to call mkdir() once per directory level. Alternatively, if you want to create multiple directories at once, make use of the makedirs() method instead (which you can see in Listing 4 below).

Advanced Bash-Scripting Guide, Generating the [list] in a for loop with command substitution; 11-8. Badname, eliminate file names in current directory containing bad characters recommended due to certain inherent problems, as pointed out in an October, Break. Terminate a foreground job. Ctl-D. Log out from a shell (similar to exit). You will only need to pass the exact path of the directory that you want to list out. The following is the python code to display all the files and directories based on the passed absolute or relative path. If path is not specified in the calling statement then the contents of current working directory will be displayed.

Batch file loop through list, BAT" just created, the user may utilize the DOS "EDIT. I need a batch script that will reference this list of file names and search through a folder and it's subfolders � Then we go back to the top, grab the next directory in the list, and repeat until we reach the end of the list. Note that although elegant, this solution has one drawback. It assumes we have at least one directory available in the current folder. If no directories are present, the loop will execute once and output ‘*/’ which may be undesired.

Comments
  • Have you tried to put dirName e.g. the to the Dictionary<string, string> (without creating a directory) just to see all entries being created.
  • I have no problems with adding 10000 files. Advice - use Path.Combine to create a directory name.
  • @Rekshino Advice taken!
  • Oh right, I am seeding the new Random instance with the same value since its happening so fast... Well done. Great point on the case insensitivity about directory and file names.
  • This is correct. I replaced the folder creation with using the loop control index and it worked. However, I do want to use the random string if possible. I updated the post to include this.
  • Well done, creating a single instance does solve it. I forget that initializing the random classes so fast, you will give it the same seed. Looking into Guid might be worth it. Also yes, using the StringBuilder would be less costlier in essence. Well done.