-1

I am making this program that randomly picks a file (not a folder) from a directory and produces a message box with that file as text. I am currently using this:

Imports System.IO
Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        For Each item In Directory.GetFiles("Directory")
            Dim filename As String = Path.GetFileName(item)
            MsgBox(filename)
        Next
    End Sub
End Class

However this prints the files in the order they were (from top to bottom) in that directory. Is there any way to print the files from a directory in a random pattern? For example, if a directory has files F1 , F2 and F3. The code I use prints them out in order of F1 , F2 and F3. Whereas I would like a program that prints them in a random order, such as F2 , F1 and F3. Also, if it's possible, I would only like the program to output one file name and stop, rather than it continuously going through the directory. For example, the message box would say F2 and close, rather than going through the list of files.

ay3
  • 3
  • 5

2 Answers2

1

You can use LINQ to order by a random number generated by a random number generator.
Because of the way LINQ works, it will essentially generate a random number for each entry and cache it, then sort by that number.

Make sure to seed your random number generator.

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim rand As New Random(System.DateTime.Now.Millisecond)
        For Each item In Directory.GetFiles("Directory").OrderBy(Function(x) rng.Next())
            Dim filename As String = Path.GetFileName(item)
            MsgBox(filename)
        Next
    End Sub
End Class

To only get the first entry, you could either break immediately after MsgBox(filename), or you could just get the first entry in the random sequence...

Dim filename As String = Directory.GetFiles("Directory").OrderBy(Function(x) rng.Next()).First()
MsgBox(filename)

Beware .First() will throw an exception if there are no files. .FirstOrDefault() will not throw an exception, but will instead set the string to null. You can check for null before displaying the messagebox if this behavior is needed.

Sichi
  • 277
  • 2
  • 10
1

First, create a shared instance of the Random class (outside your sub/event-handler):

Private Shared Rand As New Random()

Then you can use something like this (inside your sub/event-handler):

Dim files As String() = Directory.GetFiles("C:\Test")
Dim randomIndex As Integer = Rand.Next(files.Count)
MessageBox.Show(files(randomIndex))