简体   繁体   English

随机选择文件夹中的文件并移至另一个文件夹

[英]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.

相关问题 如何使用ASP将文件移动到另一个文件夹 - how to move file another folder using asp 无法将文件移动到其他文件夹 - cannot move a file into other folder 如何将DLL依赖项移动到另一个文件夹 - How to move DLL dependencies to another folder 使用WinRar压缩文件夹并移至另一个目录vb.net - Compress folder with WinRar and move to another Directory vb.net 使用File.Move将文件从源文件夹复制到目标文件夹会更改我的文件所有者 - using File.Move to copy file from source folder to destination folder changes my file owner 如何将所有文件和文件夹从当前目录移动到另一个目录(vb中名为“我的文件夹”的文件夹除外)? - How to move all files and folders from current directory to another directory excluding a folder named “My Folder” in vb? 如何使用VB将某个文件扩展名移动到一个文件夹中 - How can I move a certain file extension into one folder with VB 如何移动或更换在Visual Basic 2010文件或文件夹? - How do I move or replace a file or folder in Visual Basic 2010? 如何判断一个文件夹中的文件是否与另一个文件夹中的文件相同但已被重命名 - How to tell if file in one folder is same as file on another folder but has been renamed 从 .NET 中的同一对话框中选择文件或文件夹 - Select either a file or folder from the same dialog in .NET
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM