0

I am attempting to retrieve a random image from a directory and display it on a page. It works in essence but when I am trying to get more than one random image they are always the same! However if I debug the code and set through slowly it picks different ones. Any ideas on what I am missing here?

Class File:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

/// <summary>
/// Summary description for Photos
/// </summary>
public class Photos
{

    #region Variables

    private const string m_sImagesFolder = "/images/random/";

    #endregion

    #region Enums

    public enum PhotoType
    {
        Portrait,
        Landscape
    }

    #endregion

    public Photos()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    public string GetRandomPhoto(PhotoType pt)
    {
        return GetRandomPhoto(pt, m_sImagesFolder);
    }

    public string GetRandomPhoto(PhotoType pt, string sImagesFolder)
    {

        string sFile = null;
        string[] sExtensions = new string[] { ".png", ".jpg", ".gif" };

        if (!sImagesFolder.EndsWith("/"))
            sImagesFolder += "/";

        switch (pt)
        {

            case PhotoType.Portrait:
                sImagesFolder += "portrait/";
                break;

            case PhotoType.Landscape:
                sImagesFolder += "landscape/";
                break;

        }

        string sImagesFolder_Local = HttpContext.Current.Server.MapPath(sImagesFolder);

        try
        {
            DirectoryInfo di = new DirectoryInfo(sImagesFolder_Local);
            var rgFiles = di.GetFiles("*.*").Where(f => sExtensions.Contains(f.Extension.ToLower()));
            Random R = new Random();
            sFile = rgFiles.ElementAt(R.Next(0, rgFiles.Count())).Name;
        }
        // Probably should only catch specific exceptions throwable by the above methods.
        catch
        {

        }

        if (sFile != null)
            sFile = sImagesFolder + sFile;

        return sFile;

    }

}

Calling Page:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class academy_information_Gifted : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {

        // Get random photos
        Photos p = new Photos();
        img1.Attributes["src"] = p.GetRandomPhoto(Photos.PhotoType.Portrait);
        img2.Attributes["src"] = p.GetRandomPhoto(Photos.PhotoType.Portrait);

    }

}
Neil Ault
  • 1
  • 1
  • Also see http://stackoverflow.com/questions/14673876/multiple-random-numbers-are-the-same. When you create a `Random()` without a seed, it uses the current `Environment.TickCount` which only changes once every few milliseconds - which means you'll get the same random number if you create a `Random` faster than once every few milliseconds. – Matthew Watson Feb 13 '15 at 13:08
  • you can easily add a `Thread.Sleep(1000)` ... Random numbers are not that random, they use the timer to create random numbers, and now days, CPU's are realy fast so thread calls are sometimes executed within the same milisecond... hence the same number... adding a "fast" pause, can help, though I would, **in a live project**, use [other way to generate random numbers](http://csharpindepth.com/Articles/Chapter12/Random.aspx)... – balexandre Feb 13 '15 at 13:08

0 Answers0