select random image from folder to display in pict

2019-06-28 03:27发布

问题:

I have a picture box which reads in an image from a folder to display, instead of having the usual boring image I thought it may be nice to have a number of images in the folder and let my vb.net program randomly pick one out to use.

How can I do this?

回答1:

Try this:

Public Function GetRandomImageFilePath(ByVal folderPath As String) As String
    Dim files() As String = Directory.GetFiles(folderPath, "*.png")
    Dim random As Random = New Random()
    Return files(random.Next(0, files.Length - 1))
End Function

FYI, if you are going to call it multiple times, it would be better to create random once as a private member of the class so that it doesn't reseed the random number generation every time it's called.