来自目录的C#随机图像

时间:2015-02-13 13:04:52

标签: c# random

我正在尝试从目录中检索随机图像并将其显示在页面上。它本质上是有效的,但是当我想要获得多个随机图像时,它们总是一样的!但是,如果我调试代码并慢慢设置它会选择不同的代码。关于我在这里缺少什么的想法?

班级档案:

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;

    }

}

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

    }

}

0 个答案:

没有答案