选择目录随机文件文件、目录

2023-09-03 00:29:20 作者:ツ女紙當自強℡

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

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:\壁纸,每15分钟左右。

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

感谢。

推荐答案

http://stackoverflow.com/questions/742887/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;
    }