View Full Version : asp.net dirlist to array

12-13-2004, 10:58 PM
im trying to get a list of (jpg) files in a directory into an array so that i can select one at random to display

is there any easy way of doing this? i found an example on 4guysfromrolla but i get an error when i try and display it, all the rest of the examples say they are in an array but just display it with a datagrid so i dont know how to get the fillenames out

12-13-2004, 11:57 PM
This will grab files from a directory with a ".jpg" extension and then select a random file.

Dim dir() As String = Directory.GetFiles(Server.MapPath("\"), "*.jpg")
Dim rand As Random = New Random
If dir.Length > 0 Then
Response.Write(dir(rand.Next(0, dir.Length)))
End If

If you are wanting to grab just the file name look into the Path class (Path.GetFileName). Is this what you were needing?

12-14-2004, 08:48 AM
thisis what ithought it should be but i get an error in the first line of that

(btw i change it to .\ instead of just \ to get current dir instead of root right.. i know this works in classic asp anyway

12-14-2004, 03:11 PM
What does the error say?

12-15-2004, 09:25 AM
its just the standard asp.net error (i think i need to put a .asa somewhere or something to show a detailed error but i dont know what i have to put where :p)

12-16-2004, 12:26 PM
Public JPGPATH As String = HttpRuntime.AppDomainAppPath + "images\jpg\"

Dim di As New DirectoryInfo(JPGPATH)
Dim finf As FileInfo() = di.GetFiles()

For Each fiTemp As FileInfo In finf
... do what you like

12-16-2004, 04:42 PM
still get standard asp.net error.. how do i get real errors to display, and do i need to import anything at the top or anything?

[error still in ...Dim di As New DirectoryInfo(JPGPATH).. line]

12-16-2004, 05:30 PM
is there any rights problems on the folder ?

12-16-2004, 06:20 PM
Private Function DisplayJpg() As String
Dim Folder As String = "images\random\"
Dim JPGPATH As String = HttpRuntime.AppDomainAppPath + Folder
Dim di As New System.io.DirectoryInfo(JPGPATH)
Dim finf As System.io.FileInfo() = di.GetFiles()
Dim sc As New System.Collections.specialized.StringCollection
For Each fiTemp As System.io.FileInfo In finf
If sc.Count > 0 Then
Dim rand As Random = New Random
Dim num As Int32 = rand.Next(0, sc.Count - 1)
Return String.Format("<img src=""{0}{1}"" alt="""" />", Folder, sc(num))
Return String.Format("<img src=""{0}{1}"" alt="""" />", Folder, "default.jpg")
End If
End Function