select random file from directory

2019-01-18 10:54发布

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?

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

Thanks.

6条回答
Explosion°爆炸
2楼-- · 2019-01-18 11:45
var files = new DirectoryInfo(@"C:\dev").GetFiles();
int index = new Random().Next(0, files.Length);

Console.WriteLine(files[index].Name);
查看更多
放荡不羁爱自由
3楼-- · 2019-01-18 11:46

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
查看更多
Viruses.
4楼-- · 2019-01-18 11:46

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

查看更多
Bombasti
5楼-- · 2019-01-18 11:50

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;
    }
查看更多
兄弟一词,经得起流年.
6楼-- · 2019-01-18 11:53

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.

查看更多
干净又极端
7楼-- · 2019-01-18 11:54

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)];
查看更多
登录 后发表回答