2013-03-06 141 views
-2

劑量任何人都知道如何使用vb.net選擇現有的隨機目錄名稱(C:\驅動器)並將其位置存儲在變量中。vb.net選擇隨機文件夾名稱

我不得不GOOGEL這一個,但似乎只能夠找到例如有關的文件,而不是文件夾

+0

你可以用我的測試的答案,如果你還沒有找到這個問題的任何解決方案。 – 2013-03-07 16:17:33

回答

-2

只是做一個目錄列表,並從中選擇一個隨機項。

Dim rnd As New Random() 
Dim path As String = "C:\" 
Dim dir = New DirectoryInfo(path) 
Dim subDirs = dir.GetDirectories() 
Dim randomDir = subdirs(rnd.[Next](subDirs.Length)) 

或者,如果你喜歡的LINQ,最後一行可以是:

Dim randomDirectory = subdirs.Skip(rnd.[Next](subdirs.Length)).First() 
+0

我假設OP想要在目錄結構中的一個隨機文件不僅在頂層目錄。因此,您必須使用'SearchOption.AllDirectories',如果您沒有訪問權限(如[交接點](如http://msdn.microsoft.com/en-us/library/windows/desktop/bb968829% 28V = vs.85%29.aspx))。在C上嘗試一下。 – 2013-03-06 15:15:14

+0

我讀到它是'我怎樣才能從C:\ [目錄]'中選擇一個現有的隨機目錄名。也許問題作者可以澄清? – 2013-03-06 15:18:15

+0

我想在C:\目錄下隨機選擇一個隨機文件夾(已有的) – 2013-03-06 15:21:02

1

嘗試了這一點,希望這將滿足您的要求,

'----------------- Global Variables 
Dim xCnter = 0 
Dim xRndNo = 0 
Dim xSubdirectory As String 

Private Sub Basement() 
    Dim xGenerator As System.Random = New System.Random() 
    xRndNo = xGenerator.Next(1, 100) 
    AssignRndDirectory("C:\") 
    msgbox(subdirectory) 
End Sub 

Private Sub AssignRndDirectory(xPath as string) 
    For Each subdirectory In Directory.GetDirectories(xPath) 
     if xCnter = xRndNo then Exit sub 
     xCnter += 1 
     call AssignRndDirectory(subdirectory) 
    Next 
End Sub 

[注:此代碼沒有使用IDE進行測試,請告訴我是否有任何錯誤。]


編輯:TESTED WITH IDE

Dim xCnter = 0 
    Dim xRndNo = 0 
    Dim xSubdirectory As String 

    Private Sub Basement() 

     Dim xGenerator As System.Random = New System.Random() 
     xRndNo = xGenerator.Next(1, 100) 
     AssignRndDirectory("C:\") 
     MsgBox(xSubdirectory) 

     xCnter = 0 

    End Sub 

    Private Sub AssignRndDirectory(ByVal xPath As String) 

     Try 

      For Each Subdirectory In Directory.GetDirectories(xPath) 

       If xCnter = xRndNo Then Exit Sub 
       xSubdirectory = Subdirectory 
       xCnter += 1 
       Call AssignRndDirectory(Subdirectory) 

      Next 

     Catch ex As Exception 
      Exit Sub 
     End Try 

    End Sub 
相關問題