Randomly Assigning a File

B

brian

Hello,

Can someone tell me how I can randomly assign a file to a
variable from a directory.

Example:
Dim File as string

I need to search through 'C:/Comics/' and have the
program randomly pick a file from that path and assign it
to the variable 'File'

I will use this info to string together an image source
to randomly chage a picture. I am not interested in
using the ad rotator for this purpose.

Thanks.
 
H

Herfried K. Wagner [MVP]

Hello,

brian said:
Can someone tell me how I can randomly assign a file to a
variable from a directory.

Example:
Dim File as string

I need to search through 'C:/Comics/' and have the
program randomly pick a file from that path and assign it
to the variable 'File'

I will use this info to string together an image source
to randomly chage a picture. I am not interested in
using the ad rotator for this purpose.

Untested:

\\\
Imports System.IO
..
..
..
Dim oRand As New Random(Environment.TickCount)
Dim files() As String = Directory.GetFiles("C:\")
Dim i As Integer = oRand.Next(0, files.Length - 1)
MsgBox(files(i))
///

HTH,
Herfried K. Wagner
 
B

brian

Thanks for the reply Tom.

Can you please explain something to me. What does
'Dim intNumber As Integer = CInt(rFile.NextDouble() *
(strFiles.Length -1))' Do?

I notice you assign this to an integer and the integer is
returned. How do you then tell the image source what
file name to use since you are not looking for a file
name but instead an integer?
 
C

Chris Dunaway

Dim intNumber As Integer = CInt(rFile.NextDouble() *
(strFiles.Length -
1))

The line above seems a little inefficient. You get a double from the
random generator and then convert it to an integer. Why not just get the
integer directly using the Next function?

Dim intNumber As Integer = rFile.Next(0,strFiles.Length)

Just curious about the choice you made.

Chris
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top