Asp select random file from directory with server path

I found a solution for my problem, but I donโ€™t know which is the right way.

select an arbitrary file from the directory

public 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; } 

I use these paths but nothing works:

 "/Images/defaultImages" "~/Images/defaultImages" "Images/defaultImages" 

what is the right way?

+5
source share
1 answer

Try

 Server.MapPath("~/Images/defaultImages") 

Also make sure your defaultImages folder contains image files

0
source

All Articles