参见英文答案 >
select random file from directory 6个
有关如何改进此方法的任何建议?我目前正在使用它从壁纸目录中选择一个壁纸
有关如何改进此方法的任何建议?我目前正在使用它从壁纸目录中选择一个壁纸
我知道你不应该再使用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(); }
谢谢
紧急
解决方法
更改为使用伪随机数生成器的单个实例.
// Use a class variable so that the RNG is only created once. private Random generator; private Random Generator { get { if (this.generator == null) { this.generator = new Random(); } return this.generator; } } private string getrandomfile(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() ); int fileCount = rgFiles.Count(); if (fileCount > 0) { int x = this.Generator.Next( 0,fileCount ); file = rgFiles.ElementAt(x).FullName; } } // probably should only catch specific exceptions // throwable by the above methods. catch {} } return file; }