Creating (N) directories in a specific path in a loop stopping abruptlyCannot delete directory with Directory.Delete(path, true)How do I get the directory from a file's full path?Better way to check if a Path is a File or a Directory?How can i extract a text from a string?What could be causing an IndexOutOfRange exception with this code?Avoiding a customized Copy Directory function to go on infinite loop when copying folder into himselfWhy does Windows Explorer allow creation of folders which are too long to be moved by Directory.Move - producing PathTooLongException?how to download the azure blob snapshots using c sharp in windows form applicationHow to send a zip file from Web API 2 HttpGetCheck if a directory exists using the first 6 (or any) amount of characters
Fully submerged water bath for stove top baking?
Fast method to cut/shred glue stick into small pieces
Why would Dementors torture a Death Eater if they are loyal to Voldemort?
What prevents a US state from colonizing a smaller state?
Russian equivalents of 能骗就骗 (if you can cheat, then cheat)
Two palindromes are not enough
Position representation of spin states and spin operators
Why will we fail creating a self sustaining off world colony?
Is it theoretically possible to hack printer using scanner tray?
How does the 'five minute adventuring day' affect class balance?
How do I tell my girlfriend she's been buying me books by the wrong author for the last nine months?
Can I submit a paper to two or more journals at the same time?
Why are symbols not written in words?
Why do some PCBs have exposed plated perimeters?
A quine of sorts
What does 'in attendance' mean on an England death certificate?
A* pathfinding algorithm too slow
How do I keep a running total of data in a column in Excel?
Can I take Amul cottage cheese from India to Netherlands?
How soon after takeoff can you recline your airplane seat?
Why was Pan Am Flight 103 flying over Lockerbie?
Installed software from source, how to say yum not to install it from package?
Robots in a spaceship
What was the first science fiction or fantasy multiple choice book?
Creating (N) directories in a specific path in a loop stopping abruptly
Cannot delete directory with Directory.Delete(path, true)How do I get the directory from a file's full path?Better way to check if a Path is a File or a Directory?How can i extract a text from a string?What could be causing an IndexOutOfRange exception with this code?Avoiding a customized Copy Directory function to go on infinite loop when copying folder into himselfWhy does Windows Explorer allow creation of folders which are too long to be moved by Directory.Move - producing PathTooLongException?how to download the azure blob snapshots using c sharp in windows form applicationHow to send a zip file from Web API 2 HttpGetCheck if a directory exists using the first 6 (or any) amount of characters
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.
EDIT The GetRandomString() was an issue. Below is the code of the non working GetRandomString() how do we fix it. We always pass in a constant integer into its argument. Does it have to do with Random creating the same seed?
/// <summary>
/// Generates a random string that may contain
/// [a-z], [A-Z], and [0-9]. (62 characters.)
/// </summary>
/// <param name="length">The length of the string to generate</param>
/// <returns></returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
private string GetRandomString(int length)
Random rnd = new Random();
string rndStr = string.Empty;
if (length < 1)
throw new ArgumentOutOfRangeException("Length must be greater than 0!");
for (int i = 0; i < length; i++)
rndStr += this.charList[rnd.Next(this.charList.Length)];
return rndStr;
If you want to see if you get similar results as me or different,
copy paste the code in your IDE. Note, I am using WPF and CLR v4.0.30319
Using statements:
using System;
using System.IO;
using System.Windows.Forms;
c# wpf system.io.file system.io.directory
add a comment |
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.
EDIT The GetRandomString() was an issue. Below is the code of the non working GetRandomString() how do we fix it. We always pass in a constant integer into its argument. Does it have to do with Random creating the same seed?
/// <summary>
/// Generates a random string that may contain
/// [a-z], [A-Z], and [0-9]. (62 characters.)
/// </summary>
/// <param name="length">The length of the string to generate</param>
/// <returns></returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
private string GetRandomString(int length)
Random rnd = new Random();
string rndStr = string.Empty;
if (length < 1)
throw new ArgumentOutOfRangeException("Length must be greater than 0!");
for (int i = 0; i < length; i++)
rndStr += this.charList[rnd.Next(this.charList.Length)];
return rndStr;
If you want to see if you get similar results as me or different,
copy paste the code in your IDE. Note, I am using WPF and CLR v4.0.30319
Using statements:
using System;
using System.IO;
using System.Windows.Forms;
c# wpf system.io.file system.io.directory
1
Have you tried to putdirName
e.g. the to theDictionary<string, string>
(without creating a directory) just to see all entries being created.
– Rekshino
Mar 25 at 7:25
1
I have no problems with adding 10000 files. Advice - usePath.Combine
to create a directory name.
– Rekshino
Mar 25 at 7:56
@Rekshino Advice taken!
– Reap
Mar 25 at 15:46
add a comment |
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.
EDIT The GetRandomString() was an issue. Below is the code of the non working GetRandomString() how do we fix it. We always pass in a constant integer into its argument. Does it have to do with Random creating the same seed?
/// <summary>
/// Generates a random string that may contain
/// [a-z], [A-Z], and [0-9]. (62 characters.)
/// </summary>
/// <param name="length">The length of the string to generate</param>
/// <returns></returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
private string GetRandomString(int length)
Random rnd = new Random();
string rndStr = string.Empty;
if (length < 1)
throw new ArgumentOutOfRangeException("Length must be greater than 0!");
for (int i = 0; i < length; i++)
rndStr += this.charList[rnd.Next(this.charList.Length)];
return rndStr;
If you want to see if you get similar results as me or different,
copy paste the code in your IDE. Note, I am using WPF and CLR v4.0.30319
Using statements:
using System;
using System.IO;
using System.Windows.Forms;
c# wpf system.io.file system.io.directory
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.
EDIT The GetRandomString() was an issue. Below is the code of the non working GetRandomString() how do we fix it. We always pass in a constant integer into its argument. Does it have to do with Random creating the same seed?
/// <summary>
/// Generates a random string that may contain
/// [a-z], [A-Z], and [0-9]. (62 characters.)
/// </summary>
/// <param name="length">The length of the string to generate</param>
/// <returns></returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
private string GetRandomString(int length)
Random rnd = new Random();
string rndStr = string.Empty;
if (length < 1)
throw new ArgumentOutOfRangeException("Length must be greater than 0!");
for (int i = 0; i < length; i++)
rndStr += this.charList[rnd.Next(this.charList.Length)];
return rndStr;
If you want to see if you get similar results as me or different,
copy paste the code in your IDE. Note, I am using WPF and CLR v4.0.30319
Using statements:
using System;
using System.IO;
using System.Windows.Forms;
c# wpf system.io.file system.io.directory
c# wpf system.io.file system.io.directory
edited Mar 25 at 15:46
Reap
asked Mar 25 at 5:48
ReapReap
155 bronze badges
155 bronze badges
1
Have you tried to putdirName
e.g. the to theDictionary<string, string>
(without creating a directory) just to see all entries being created.
– Rekshino
Mar 25 at 7:25
1
I have no problems with adding 10000 files. Advice - usePath.Combine
to create a directory name.
– Rekshino
Mar 25 at 7:56
@Rekshino Advice taken!
– Reap
Mar 25 at 15:46
add a comment |
1
Have you tried to putdirName
e.g. the to theDictionary<string, string>
(without creating a directory) just to see all entries being created.
– Rekshino
Mar 25 at 7:25
1
I have no problems with adding 10000 files. Advice - usePath.Combine
to create a directory name.
– Rekshino
Mar 25 at 7:56
@Rekshino Advice taken!
– Reap
Mar 25 at 15:46
1
1
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.– Rekshino
Mar 25 at 7:25
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.– Rekshino
Mar 25 at 7:25
1
1
I have no problems with adding 10000 files. Advice - use
Path.Combine
to create a directory name.– Rekshino
Mar 25 at 7:56
I have no problems with adding 10000 files. Advice - use
Path.Combine
to create a directory name.– Rekshino
Mar 25 at 7:56
@Rekshino Advice taken!
– Reap
Mar 25 at 15:46
@Rekshino Advice taken!
– Reap
Mar 25 at 15:46
add a comment |
3 Answers
3
active
oldest
votes
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());
1
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.
– Reap
Mar 27 at 18:02
add a comment |
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.
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 theStringBuilder
would be less costlier in essence. Well done.
– Reap
Mar 27 at 18:05
add a comment |
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"));
codesample please
– Maciej S.
Mar 25 at 14:12
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.
– Reap
Mar 25 at 15:43
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55331879%2fcreating-n-directories-in-a-specific-path-in-a-loop-stopping-abruptly%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
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());
1
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.
– Reap
Mar 27 at 18:02
add a comment |
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());
1
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.
– Reap
Mar 27 at 18:02
add a comment |
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());
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());
edited Mar 25 at 18:18
answered Mar 25 at 17:47
Lana PelmeshkinaLana Pelmeshkina
3481 silver badge7 bronze badges
3481 silver badge7 bronze badges
1
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.
– Reap
Mar 27 at 18:02
add a comment |
1
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.
– Reap
Mar 27 at 18:02
1
1
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.
– Reap
Mar 27 at 18:02
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.
– Reap
Mar 27 at 18:02
add a comment |
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.
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 theStringBuilder
would be less costlier in essence. Well done.
– Reap
Mar 27 at 18:05
add a comment |
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.
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 theStringBuilder
would be less costlier in essence. Well done.
– Reap
Mar 27 at 18:05
add a comment |
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.
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.
answered Mar 26 at 3:35
CoreyCorey
11.3k1 gold badge24 silver badges55 bronze badges
11.3k1 gold badge24 silver badges55 bronze badges
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 theStringBuilder
would be less costlier in essence. Well done.
– Reap
Mar 27 at 18:05
add a comment |
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 theStringBuilder
would be less costlier in essence. Well done.
– Reap
Mar 27 at 18:05
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.– Reap
Mar 27 at 18:05
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.– Reap
Mar 27 at 18:05
add a comment |
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"));
codesample please
– Maciej S.
Mar 25 at 14:12
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.
– Reap
Mar 25 at 15:43
add a comment |
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"));
codesample please
– Maciej S.
Mar 25 at 14:12
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.
– Reap
Mar 25 at 15:43
add a comment |
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"));
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"));
edited Mar 25 at 14:36
answered Mar 25 at 13:59
Lana PelmeshkinaLana Pelmeshkina
3481 silver badge7 bronze badges
3481 silver badge7 bronze badges
codesample please
– Maciej S.
Mar 25 at 14:12
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.
– Reap
Mar 25 at 15:43
add a comment |
codesample please
– Maciej S.
Mar 25 at 14:12
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.
– Reap
Mar 25 at 15:43
codesample please
– Maciej S.
Mar 25 at 14:12
codesample please
– Maciej S.
Mar 25 at 14:12
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.
– Reap
Mar 25 at 15:43
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.
– Reap
Mar 25 at 15:43
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55331879%2fcreating-n-directories-in-a-specific-path-in-a-loop-stopping-abruptly%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
Have you tried to put
dirName
e.g. the to theDictionary<string, string>
(without creating a directory) just to see all entries being created.– Rekshino
Mar 25 at 7:25
1
I have no problems with adding 10000 files. Advice - use
Path.Combine
to create a directory name.– Rekshino
Mar 25 at 7:56
@Rekshino Advice taken!
– Reap
Mar 25 at 15:46