加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 从目录中选择随机文件[复制]

发布时间:2020-12-15 19:48:14 所属栏目:百科 来源:网络整理
导读:参见英文答案 select random file from directory????????????????????????????????????6个 有关如何改进此方法的任何建议?我目前正在使用它从壁纸目录中选择一个壁纸 我知道你不应该再使用arraylist了,但我想不出一个altrnative 我也不确定如何在目录信息
参见英文答案 > select random file from directory????????????????????????????????????6个
有关如何改进此方法的任何建议?我目前正在使用它从壁纸目录中选择一个壁纸

我知道你不应该再使用arraylist了,但我想不出一个altrnative
我也不确定如何在目录信息中过滤不止一种类型的文件(即jpg gif png).

任何建议或调整都会很棒

private string getrandomfile(string path)
        {
            ArrayList al = new ArrayList();
            DirectoryInfo di = new DirectoryInfo(path);
            FileInfo[] rgFiles = di.GetFiles("*.*");
            foreach (FileInfo fi in rgFiles)
            {
                al.Add(fi.FullName);
            }

            Random r = new Random();
            int x = r.Next(0,al.Count);

            return al[x].ToString();

        }

谢谢

紧急

解决方法

更改为使用伪随机数生成器的单个实例.

// Use a class variable so that the RNG is only created once.
private Random generator;
private Random Generator
{
    get
    {
        if (this.generator == null)
        {
           this.generator = new Random();
        }
        return this.generator;
    }
}
private string getrandomfile(string path)
{
    string file = null;
    if (!string.IsNullOrEmpty(path))
    {
        var extensions = new string[] { ".png",".jpg",".gif" };
        try
        {
            var di = new DirectoryInfo(path);
            var rgFiles = di.GetFiles("*.*")
                            .Where( f => extensions.Contains( f.Extension
                                                               .ToLower() );
            int fileCount = rgFiles.Count();
            if (fileCount > 0)
            {
                int x = this.Generator.Next( 0,fileCount );
                file = rgFiles.ElementAt(x).FullName;
            }
        }
        // probably should only catch specific exceptions
        // throwable by the above methods.
        catch {}
    }
    return file;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读