kockiren
kockiren

Reputation: 711

Access to Random Files in Random Directories in C#

For a testsuite to test some Replication scenarios I write a FileAccesser. This should access random files (in random subdirectories) in a given directory and Delete, Create, Rename and change the file or/and content. I am looking for a way to access a random file in a random subdirectory. Any suggestions?

My Solution to get a List of all files in all Subdirectories is:

var _Directory = new DirectoryInfo(args[1]);
var _Files = _Directory.GetFiles("*", SearchOption.AllDirectories);

Now i can access to a Random File with

Random _Random = new Random();
var _RandomFile = _Files.ElementAt(_Random.Next(_Files.Count()));

THX for your help.

Upvotes: 1

Views: 709

Answers (3)

Mohamed Abed
Mohamed Abed

Reputation: 5113

  • Create a list of strings, each string represent a file path (Directory\FileName.ext)
  • Generate random number 0 - length of the string-1
  • Get the index based on the random numnber

Upvotes: 1

TeamWild
TeamWild

Reputation: 2550

I think I understand what you want to do but the use of randomness for testing seems like the wrong thing to do here.

I hope I'm not teaching anyone to suck eggs here but tests are supposed to be repeatable and measurable. If any test fails you need to be able to step through and identify what went wrong and correct it.

If you can modify the properties and contents of a file in one directory, then you should be able to do it in any as long as all the parameters of the test are the same. If the parameters of the test change then the scope of the test increases (eg, permissions on a directory or file make it read-only).

Upvotes: 4

Ankur
Ankur

Reputation: 33637

You could do something like :

  • Create a List of all directories (as list of string)
  • For each directory create a List of files in it.
  • Using a Random generator generate a number between 0 and list of dir count.
  • Select the dir from the list based on the above generated number as index.
  • Apply the last 2 steps for selecting a random file for above selected directory.

Upvotes: 2

Related Questions