• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 520
  • Last Modified:

Displaying random image from an array of images in ASP.NET using C#...


I have the following code that I'm trying to display an image randomly selected from a list of images in an array, but it doesn't seem to work.  Please help!

Very much appreciated.
<asp:Image ID="imgRandom" runat="server" Height="50px" Width="50px" />
    protected void Page_Load(object sender, EventArgs e)
        string imageDir = "images_random/";
        string physicalPath = Server.MapPath("/images_random");
        string[] filePath = Directory.GetFiles(physicalPath, "*.gif"); // i know all my images are gifs
        DirectoryInfo dirInfo = new DirectoryInfo(physicalPath);
        FileInfo[] imageFiles = dirInfo.GetFiles();
        string listFiles = "";
        int i = 0;
        foreach (FileInfo file in imageFiles)
            listFiles += imageDir + file.Name;
            if (i < imageFiles.Length)
                listFiles += ",";
        string path = Request.ApplicationPath + GetRandomImage(listFiles);
        imgRandom.ImageUrl = path; // display the random image
    protected string GetRandomImage(string files)
        Random r = new Random();
        string[] images = new string[] { files }; // this "files" variable should spit out the same list of images as those in the next commented line. If I comment out this line, and uncomment the next line, it works.
        //string[] images = new string[] { "images_random/someimage1002007.gif", "images_random/someimage-2008.gif", "images_random/someimage-2007.gif", "images_random/someimage-1987.gif", "images_random/someimage-1995.gif", "images_random/someimage-2001.gif", "images_random/someimage-2004.gif", "images_random/someimage-2006.gif" };
        return images[r.Next(0, images.Length)]; // this line works

Open in new window

  • 2
1 Solution

string[] images  = files.Split(',');

This will return an array of strings
WebAppDeveloperAuthor Commented:
It works. Thanks very much!
Glad to be of service. If you could mark my response as the answer that would be awesome. Im racing a friend tonight for points :)

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now