C# 从目录中选择随机文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/742685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 23:26:34  来源:igfitidea点击:

select random file from directory

c#.netfilerandom

提问by Crash893

I've seen a few examples but none so far in C#, what is the best way to select a random file under a directory?

我在 C# 中看过一些例子,但到目前为止还没有,在目录下选择随机文件的最佳方法是什么?

In this particular case I want to select a wallpaper from "C:\wallpapers" every 15 or so minutes.

在这种特殊情况下,我想每 15 分钟左右从“C:\wallpapers”中选择一张壁纸。

Thanks.

谢谢。

采纳答案by Crash893

select random file from directory

从目录中选择随机文件

private string getrandomfile2(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()));
                Random R = new Random();
                file = rgFiles.ElementAt(R.Next(0,rgFiles.Count())).FullName;
            }
            // probably should only catch specific exceptions
            // throwable by the above methods.
            catch {}
        }
        return file;
    }

回答by Mouk

Get all files in an array and then retrieve one randomly

获取数组中的所有文件,然后随机检索一个

var rand = new Random();
var files = Directory.GetFiles("c:\wallpapers","*.jpg");
return files[rand.Next(files.Length)];

回答by leora

why not just:

为什么不只是:

  1. get the files into an array
  2. use the Random class to select a number that is random between 0 and files.Length
  3. Grab the file from the array using the random number as the index
  1. 将文件放入数组
  2. 使用 Random 类选择一个在 0 和 files.Length 之间随机的数字
  3. 使用随机数作为索引从数组中获取文件

回答by Lance Harper

var files = new DirectoryInfo(@"C:\dev").GetFiles();
int index = new Random().Next(0, files.Length);

Console.WriteLine(files[index].Name);

回答by Daniel A. White

Use the Directory.GetFiles(...)to get the array of filenames and use the Randomclass to select a random file.

使用Directory.GetFiles(...)获取文件名数组并使用Random类选择随机文件。

回答by Jason Cohen

If you're doing this for wallpapers, you don't want to just select a file at random because it won't appear random to the user.

如果您要为壁纸执行此操作,您不想只是随机选择一个文件,因为它不会对用户显示随机。

What if you pick the same one three times in a row? Or alternate between two?

如果你连续三次选择同一个怎么办?还是两者交替?

That's "random," but users don't like it.

这是“随机的”,但用户不喜欢它。

See this post about how to display random pictures in a way users will like.

请参阅这篇关于如何以用户喜欢的方式显示随机图片的帖子。

回答by Nick Kovalsky

Just my 5 cents, code for an mvc action, using cookies so we do not repeat the same filename twice:

只是我的 5 美分,用于 mvc 操作的代码,使用 cookie,因此我们不会重复相同的文件名两次:

        [AllowAnonymous]
        //-------------------------------------------------------------
        public async Task<ActionResult> RandomBackground()
        //-------------------------------------------------------------
        {
            var basePath = "~/Content/images/backgrounds";
            var dir = System.Web.Hosting.HostingEnvironment.MapPath(basePath);

            var rand = new Random();
            var files = System.IO.Directory.GetFiles(dir, "*.jpg");
            if (files!=null)
            {
                var cookie = "Background";
                var pickedFile = "";
                var fileName = "";
                var oldFilename = "";
                while ((oldFilename == fileName) && files.Count<string>()>1)
                {
                    oldFilename = ReadControllerCookie(cookie);
                    pickedFile = files[rand.Next(files.Length)];
                    fileName = System.IO.Path.GetFileName(pickedFile);
                }
                SaveControllerCookie(cookie, fileName);
                return Content(fileName);
            }
            return new EmptyResult();
        }

Used as:

用作:

<img src="~/Content/images/backgrounds/@Html.Action("RandomBackground", "YourControllerName")">