Reputation: 31
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
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