开发者

How do I get the path of a random folder?

开发者 https://www.devze.com 2022-12-24 04:54 出处:网络
Like start at c:\\ (or whatever the main drive is) and then randomly take routes?Not even sure how to do that.

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

开发者_C百科
public sealed static class FolderHelper
{
    public static string GetRandomFolder()
    {
        // do work
    }
}


I rolled a die and came up with this answer:

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

Or you could use Random.Next().


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];


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.


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消