select random file from directory

Get all files in an array and then retrieve one randomly

var rand = new Random();
var files = Directory.GetFiles("c:\\wallpapers","*.jpg");
return files[rand.Next(files.Length)];

select random file from directory

private string getrandomfile2(string path)
    {
        string file = null;
        if (!string.IsNullOrEmpty(path))
        {
            var extensions = new string[] { ".png", ".jpg", ".gif" };
            try
            {
                var di = new DirectoryInfo(path);
                var rgFiles = di.GetFiles("*.*").Where( f => extensions.Contains( f.Extension.ToLower()));
                Random R = new Random();
                file = rgFiles.ElementAt(R.Next(0,rgFiles.Count())).FullName;
            }
            // probably should only catch specific exceptions
            // throwable by the above methods.
            catch {}
        }
        return file;
    }

If you're doing this for wallpapers, you don't want to just select a file at random because it won't appear random to the user.

What if you pick the same one three times in a row? Or alternate between two?

That's "random," but users don't like it.

See this post about how to display random pictures in a way users will like.

Tags:

C#

.Net

File

Random