How do I get the path of a random folder?

2019-09-07 13:53发布

问题:

Like start at c:\ (or whatever the main drive is) and then randomly take routes? Not even sure how to do that.

public sealed static class FolderHelper
{
    public static string GetRandomFolder()
    {
        // do work
    }
}

回答1:

Try getting a list of all the folders in the directory, then generate a random number up to the number of folders, then choose the folder that relates to your random number.

System.IO.DirectoryInfo[] subDirs;
System.IO.DirectoryInfo root;
// assign the value of your root here
subDirs = root.GetDirectories();
Random random = new Random();
int directory = random.Next(subDirs.Length);
System.IO.DirectoryInfo randomDirectory = subDirs[directory];


回答2:

I rolled a die and came up with this answer:

  public static string GetRandomFolder()
    {
        return "4";
    }

Or you could use Random.Next().



回答3:

First of all you need something to pick from, for example all subdirectories in a directory, so then you need to specify that parent directory. Then you just get the directories and pick one by random:

public static string GetRandomFolder() {
  string parentFolder = @"c:\some\folder\somewhere";
  string[] folders = Directory.GetDirectories(parentFolder);
  Random rnd = new Random();
  return folders[rnd.Next(folders.Length)];
}

If you are going to do this more than once, you should consider making a class of it, so that you can read in the folders and create the random generator and store in the class when you create an instance of the class, and then just use them in the method.



回答4:

I use this code to get a random folder from sub-folders tree of a given root folder

private string GetRandomFolder(string root)
{
  var rnd = new Random();
  var path = root;
  var depth = rnd.Next(0, 7);

  for (int i = 0; i < depth; i++)
  {
    path = this.GetRandomFolder(path);
    if (path == "")
      break;
  }

  return output;
}
private string GetRandomSubFolder(string root)
{
  var di = new DirectoryInfo(root);
  var dirs = di.GetDirectories();
  var rnd = new Random();

  if (dirs.Length == 0)
    return "";

  return dirs[rnd.Next(0, dirs.Length - 1)].FullName;
}