Crash893
Crash893

Reputation: 11702

select random file from directory

I've seen a few examples but none so far in C#, what is the best way to select a random file under a directory?

In this particular case I want to select a wallpaper from "C:\wallpapers" every 15 or so minutes.

Thanks.

Upvotes: 19

Views: 25785

Answers (7)

Nick Kovalsky
Nick Kovalsky

Reputation: 6452

Just my 5 cents, code for an mvc action, using cookies so we do not repeat the same filename twice:

        [AllowAnonymous]
        //-------------------------------------------------------------
        public async Task<ActionResult> RandomBackground()
        //-------------------------------------------------------------
        {
            var basePath = "~/Content/images/backgrounds";
            var dir = System.Web.Hosting.HostingEnvironment.MapPath(basePath);

            var rand = new Random();
            var files = System.IO.Directory.GetFiles(dir, "*.jpg");
            if (files!=null)
            {
                var cookie = "Background";
                var pickedFile = "";
                var fileName = "";
                var oldFilename = "";
                while ((oldFilename == fileName) && files.Count<string>()>1)
                {
                    oldFilename = ReadControllerCookie(cookie);
                    pickedFile = files[rand.Next(files.Length)];
                    fileName = System.IO.Path.GetFileName(pickedFile);
                }
                SaveControllerCookie(cookie, fileName);
                return Content(fileName);
            }
            return new EmptyResult();
        }

Used as:

<img src="~/Content/images/backgrounds/@Html.Action("RandomBackground", "YourControllerName")">

Upvotes: 0

Crash893
Crash893

Reputation: 11702

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

Upvotes: 8

Lance Harper
Lance Harper

Reputation: 2226

var files = new DirectoryInfo(@"C:\dev").GetFiles();
int index = new Random().Next(0, files.Length);

Console.WriteLine(files[index].Name);

Upvotes: 6

Jason Cohen
Jason Cohen

Reputation: 83011

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.

Upvotes: 10

Daniel A. White
Daniel A. White

Reputation: 190935

Use the Directory.GetFiles(...) to get the array of filenames and use the Random class to select a random file.

Upvotes: 1

leora
leora

Reputation: 196479

why not just:

  1. get the files into an array
  2. use the Random class to select a number that is random between 0 and files.Length
  3. Grab the file from the array using the random number as the index

Upvotes: 1

Mouk
Mouk

Reputation: 1737

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

Upvotes: 30

Related Questions