2016-03-04 65 views
0

目錄和出口在DGV有我的代碼:我如何循環文件在VB.NET

For i As Integer = 0 To lstDir.Items.Count - 1 
     For Each File As String In Directory.GetFiles(lstDir.Items(i)) 
       Fname = File.ToString.Substring(File.LastIndexOf("\") + 1) 
       i = +1 

       If File.Contains(".zip") Then 
        res = "" 
        For Each Str As Char In Fname 
         If IsNumeric(Str) Then 
         res = res & Str 
         End If 
        Next 

        For x As Integer = 0 To lstDir.Items.Count - 1 
         For Each newFile As String In Directory.GetFiles(lstDir.Items(x)) 
          If newFile.Contains(res) Then 
          dgContents.Rows.Add(Fname) 
          End If 
         Next 
        Next 

       End If 

    Next 
Next 

想我的目錄包含以下文件:

abc123.pdf 
def456.zip 
ghi123.zip 
jkl123.xml 
mno456.pdf 
pqr456.xml 

,我需要選擇剛纔的所有.zip文件,獲取zip文件名中的數字,然後再次循環目錄,以從zip中搜索具有相同編號的文件,然後將其添加到datagrid。我的問題是,我的代碼顯示輸出是這樣的:的

def456.zip 
def456.zip 
def456.zip 
ghi123.zip 
ghi123.zip 
ghi123.zip 

代替

def456.zip 
mno456.pdf 
pqr456.xml 
ghi123.zip 
abc123.pdf 
jkl123.xml 

請幫助...

回答

0

我不知道如果我理解你。我建議你使用下一個代碼。

Sub爲通過文件循環用.zip延伸在一個給定的路徑:

Imports System.IO 

    Public Sub GetFilesFromDir(path As String) 
       ' Make a reference to a directory. 
       Dim di As New DirectoryInfo(path) 
       ' Get a reference to each file in that directory. 
       Dim fiArr As FileInfo() = di.GetFiles() 
       ' Display the names of the files. 
       Dim file As FileInfo 
       Dim fileName As String = "" 
       For Each file In fiArr 
        If file.Extension = ".zip" Then 
         Console.WriteLine("------------- {0} -----------", file.Name) 
         fileName = System.IO.Path.GetFileNameWithoutExtension(path & "\" & file.Name) 
         DisplayFilesByNumber(fiArr, fileName) 
        End If 
       Next 
    End Sub 

DisplayFilesByNumberSub其中通過文件環路包含一個給定字符串(在這種情況下,在數fileName)完成。

Public Sub DisplayFilesByNumber(fiArr As FileInfo(), fileName As String) 
     For Each fileByNumber In fiArr 
      If fileByNumber.Name.Contains(GetNumbers(fileName)) Then 
       Console.WriteLine(fileByNumber) 
      End If 
     Next 
End Sub 

Sub需要一個簡單的函數來獲得在fileName數量。

Imports.Text.RegularExpressions 

    Public Function GetNumbers(fileName As String) As String 
      GetNumbers = Regex.Replace(fileName, "[^0-9]", String.Empty) 
    End Function 

這給下一輸出:

------------- def456.zip ----------- 
def456.zip 
mno456.pdf 
pqr456.xml 
------------- ghi123.zip ----------- 
abc123.pdf 
ghi123.zip 
jkl123.xml 

我希望我理解正確你。我沒有將值存儲在DGV中,但我相信您可以應對這一點。