选择目录随机文件 [英] select random file from directory
本文介绍了选择目录随机文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经看到了一些例子,但没有到目前为止,在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.
感谢。
推荐答案
<一个href="http://stackoverflow.com/questions/742887/select-random-file-from-directory">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;
}
这篇关于选择目录随机文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文