Link to home
Start Free TrialLog in
Avatar of smagnus1
smagnus1

asked on

Random Image Display

Hi all,

I know this is a "dumb" question, but here goes.  Given a folder (Call it C:\Test\ for short) filled with images, I want, on page load, to load a random photo from that folder.  My code so far is attached.  Thanks in advance for any help.
Dim di As New IO.DirectoryInfo("c:\Test\")
        Dim diar1 As IO.FileInfo() = di.GetFiles()
        Dim dra As IO.FileInfo
 
        Dim xCount As Integer
 
        For Each dra In diar1
            xCount = xCount + 1
        Next
 
        xCount = xCount - 1
 
        Dim rnd As Integer, randomNum As New Random
        rnd = randomNum.Next(1, xCount)
        
 
        Image1.ImageUrl = ???

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of gnoon
gnoon
Flag of Thailand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of smagnus1
smagnus1

ASKER

Thanks.  I understand the importance of bulletproofing the code (aka, what if no file exists, etc.) and do appreciate it, but I am simply trying to get the darn thing to work right now.  I feel relatively comfortable performing the default image task and whatnot, but I am hung @:

Image1.ImageUrl = "c:\1\" & CStr(dra(rnd))

How do I set the image to a random?  I know, for instance, that the above code simply will not do this.  I appologize for being vague.  Thanks again.
I have found a link to send this in the right direction.

http://juranger.spaces.live.com/Blog/cns!8B711EA4E33A8804!187.entry

Thanks again, all
Image1.ImageUrl is web relative path on IIS, not physical path on server. So, you should not assign the URL like that.

>How do I set the image to a random?

Well, I see your concept in code above. You read info of files into an array (diar1), 10 files for example and lets say position 0-9. Then, you random a number between 0 and 9 to pick up a file which is now random selected. You can get the random file like this

...

Dim sDraURL As String = "image/defaultimage.jpg"

If rnd >= 0 And rnd < diar1.Length Then
    sDraURL = "filerelativepath/" & diar1(rnd).Name
End If

Image1.ImageUrl = sDraURL
>I have found a link to send this in the right direction.

Glad to hear that :)