vendredi 13 février 2015

C# Random Image from Directory [duplicate]


This question already has an answer here:




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

}

}




Aucun commentaire:

Enregistrer un commentaire