Samssonart
Samssonart

Reputation: 3593

Get file name with system IO

I'm working on a C# script that has to access a random file during runtime, the problem is that the files are being generated on the fly by another source and I have no means of knowing their names, I have solved a first issue which is to get how many files there are in my working directory:

            s = @"C:\Imagenes";
            System.IO.DirectoryInfo d = new System.IO.DirectoryInfo(s);
    int files;
    files = d.GetFiles().Length;
    Debug.Log(files.ToString());
    return files;

Now I would like to acces a random element in my working dicrectory, but since I don't have a clue what their names are, is there a way to get their names by index or something?

Upvotes: 1

Views: 3510

Answers (4)

Bernhard Kircher
Bernhard Kircher

Reputation: 4172

Not sure why you want a random file, but this should work (except files get deleted during calculation of length and getting a rondom one)

int length = d.GetFiles().Length;
Random rnd = new Random();
var randomFile = d.GetFiles().ElementAt(rnd.Next(0, length-1);

Upvotes: 0

jcvandan
jcvandan

Reputation: 14314

You need to use the FileInfo objects that are returned by d.GetFiles():

DirectoryInfo d = new DirectoryInfo("c:\\path");

foreach (FileInfo file in d.GetFiles())
{
    string name = file.Name;
}

Upvotes: 1

Yahia
Yahia

Reputation: 70369

try

FileInfo[] fileinfos = d.GetFiles();

foreach (FileInfo FI in fileinfos)
{
string fullname = FI.FullName;
string name = FI.Name;

// do someting...
}

see

Upvotes: 0

Zenwalker
Zenwalker

Reputation: 1919

DirectoryInfo.GetFiles will give you array of fileInfo objects. From that you can get the file name using FileInfo.Name

Upvotes: 6

Related Questions