Bobby X
asked on
Displaying random image from an array of images in ASP.NET using C#...
Hi,
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.
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)
{
i++;
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
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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 :)
ASKER