Cra*_*893 3 .net c# random file
有关如何改进此方法的任何建议?我目前正在使用它从壁纸目录中选择一个壁纸
我知道你不应该再使用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();
}
Run Code Online (Sandbox Code Playgroud)
谢谢
紧急
sip*_*wiz 10
为什么不使用LINQ:
var files = Directory.GetFiles(path, "*.*").Where(s => Regex.Match(s, @"\.(jpg|gif|png)$").Success);
string randFile = path + files.ToList()[r.Next(0, files.Count())];
Run Code Online (Sandbox Code Playgroud)
一如既往 - 给猫皮肤涂抹的方法不止一种.我已经建立了tvanfosson(正确)答案,而不是因为这更"正确"; 但是因为我认为这是一种有用的方法.
private static string getRandomFile(string path)
{
try
{
var extensions = new string[] { ".png", ".jpg", ".gif" };
var di = new DirectoryInfo(path);
return (di.GetFiles("*.*")
.Where(f => extensions.Contains(f.Extension
.ToLower()))
.OrderBy(f => Guid.NewGuid())
.First()).FullName ;
}
catch { return ""; }
}
Run Code Online (Sandbox Code Playgroud)