Random Directories

  • Thread starter Thread starter Default User
  • Start date Start date
D

Default User

Hi too all,

I'm trying to write a simple program which will find all the folders in the
c drive, but i'm having problems
I've managed to search the root of c drive folders but having problems with
search them. Here is the code i've been so far

using System;

using System.Collections.Generic;

using System.Text;

using System.IO;

namespace ConsoleApplication1

{

class Program

{


static void Main(string[] args)

{

string[] folders = Directory.GetDirectories(@"C:\");



int p = folders.Length;

System.Random RandNum = new System.Random();

int mRandomNumber = RandNum.Next(1, p);

Console.WriteLine(folders.GetValue(mRandomNumber)+@"\");

}

}

}



can someone offer a helping hand?

thanks
 
Hi Default User,

You aren't saying what specific problem you have, but I suspect you mean you can't get the subdirectories.

You need to recursively call a method that retrieves directory names until there are none left.

static void Main()
{
ArrayList list = new ArrayList();
GetDirectories("C:\", list);
Random rand = new Random();
int num = rand.Next(0, list.Count);
Console.WriteLine(list[num]);

// Don't use the line below. I merely added it to show that
// you can in fact combine the above three lines.
// For clarity reasons and readability you should not use this.
// Console.WriteLine(list[new Random().Next(0, list.Count)]);
}

static void GetDirectories(string dir, ArrayList storage)
{
string[] dirs = Directory.GetDirectories(dir);
foreach(string s in dirs)
{
storage.Add(s);
GetDirectories(s, storage);
}
}

Of course, you will now bump into exceptions when you can't read the subdirectory. To solve this you can use a try/catch block and ignore those directories that throw an exception

try
{
GetDirectories(s, storage);
}
catch
{
}
 
Hi too all,

I'm trying to write a simple program which will find all the folders in the
c drive, but i'm having problems
I've managed to search the root of c drive folders but having problems with
search them. Here is the code i've been so far

using System;

using System.Collections.Generic;

using System.Text;

using System.IO;

namespace ConsoleApplication1

{

class Program

{


static void Main(string[] args)

{

string[] folders = Directory.GetDirectories(@"C:\");



int p = folders.Length;

System.Random RandNum = new System.Random();

int mRandomNumber = RandNum.Next(1, p);

Console.WriteLine(folders.GetValue(mRandomNumber)+@"\");

}

}

}



can someone offer a helping hand?

thanks


Have a look at the foreach loop, and run it through your folders
array.

rossum



The ultimate truth is that there is no ultimate truth
 
Back
Top