Işık Işiten Iki
Işık Işiten Iki

Reputation: 31

Randomly Select A File in folder & Move To Another Folder

I need to select a file from a directory and move to another directory. In order to do that I need to select a file randomly.

I need to select a random file (any ext can be) but I dont know how to use return because I am new to VB.NET. So please give ideas and code.

Upvotes: 1

Views: 1983

Answers (1)

BlackCap
BlackCap

Reputation: 1094

Like this?

Sub MoveRandomFile(from$, to$)
    Static r As New Random
    Dim Files = New IO.DirectoryInfo([from]).GetFiles
    Dim FileToMove = Files(r.Next(0, Files.Count))

    IO.File.Move(FileToMove.FullName, FileToMove.FullName.Replace([from], [to]))
End Sub

Or if you just want to return a random file:

Function GetRandomFile(folder$) As IO.FileInfo
    Static r As New Random
    Dim Files = New IO.DirectoryInfo(folder).GetFiles

    Return Files(r.Next(0, Files.Count))
End Function

The static keyword creates the variable the first time the method is called, and keeps it for the next time. The reason we need to do that is because the random object uses a seed, like in Minecraft, and this seed is generated using information about the running process. So if you create a new random object each time it will choose the same file each time.

Upvotes: 2

Related Questions