How can I select a random folder from a list of folders?
i want to get a random directory from a specified directory, for example, the desktop.
im not sure how to do this, this and the only thing I'm having trouble with for my application
for example i have 5 different directories on the desktop called
Dir1 Dir2 Dir3, etc...
i would like to get Dir3, then maybe Dir1, after that maybe Dir3 again, and so on. i want to get a random directory from the d开发者_运维百科esktop...dont really know how to explain it any better...
A specified a directory - a directory that i specify maybe in a text box for example. or a folder browser dialog
also i just want to get the path of the directory, i dont want to do anything to it.
If anyone could provide some information I would be greatly appreciative :D
thanks everyone!
This kind of smells like homework to me. But I've got some time to kill. The function below takes a path as a string and returns a random subfolder as a string.
Public Function GetRandomSubFolder(path As String) As String
''//Static create a Random object so that we do not create a new one each time
Static R As New Random()
''//Sanity check
If Not System.IO.Directory.Exists(path) Then Throw New System.IO.DirectoryNotFoundException("path")
''//Get the subfolders as an array
Dim SubFolders = System.IO.Directory.GetDirectories(path)
''//Sanity check
If SubFolders.Count = 0 Then Throw New ApplicationException("Could not find any subfolders")
''//Get a random number. The second parameter is exclusive so (0,4) will always return 3 as a maximum
Dim RandomIndex As Integer = R.Next(0, SubFolders.Count)
''//Return the path at that index
Return SubFolders(RandomIndex)
End Function
That was fun! :-D
Just change the ParentFolder
to the folder you want to scan.
RandomFolder.bat
@Echo Off
Set ParentFolder=C:\Users\Me\Desktop
Set List=
For /F "tokens=* delims=" %%d In ('Dir /b /ad "%ParentFolder%"') Do Call :AddToList "%%d"
Set FolderCount=0
Call :CountFolders %List%
Set /a FolderIndex=%Random% %% %FolderCount%
Call :SelectRandomFolder %List%
Echo %RandomFolder%
Exit /B
:AddToList
Set List=%List% %1
Exit /B
:CountFolders
Shift
If "%~1"=="" Exit /B
Set /a FolderCount=%FolderCount% + 1
Goto :CountFolders
:SelectRandomFolder
Set RandomFolder=%~1
If %FolderIndex%==0 Exit /B
Set /a FolderIndex=%FolderIndex% - 1
Shift
Goto :SelectRandomFolder
精彩评论