[英]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
. 我需要选择一个随机文件(任何扩展名都可以),但是我不知道如何使用
return
因为我是VB.NET
新手。 So please give ideas and code. 因此,请提供想法和代码。
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. static关键字在第一次调用该方法时创建变量,并在下一次保留该变量。 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.
我们需要这样做的原因是因为随机对象使用种子,例如在Minecraft中,并且使用有关运行进程的信息来生成该种子。 So if you create a new random object each time it will choose the same file each time.
因此,如果每次创建一个新的随机对象,它将每次都选择相同的文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.