Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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;
- }
- var files = Directory.GetFiles(path, "*.*").Where(s => Regex.Match(s, @".(jpg|gif|png)$").Success);
- string randFile = path + files.ToList()[r.Next(0, files.Count())];
- 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 ""; }
- }
- 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;
- }
Add Comment
Please, Sign In to add comment