2015-10-19 67 views
0

我有一個需要通過行的文本文件行看的節目,線條看起來像這樣:使用數組來搜索文件VB

10-19-2015 Brett Reinhard All Bike Yoga Run the Studio Design Your Own Strength 

這些由在文本文件中製表符分隔。

我想要做的就是看第二個值,在這種情況下,「佈雷特萊因哈德」和全系列移動到名爲「佈雷特萊因哈德」另一個文本文件

我想用一個數組來檢查的查看行中的第二個'列'是否與給定數組中的任何值相匹配,如果是,我想執行特定操作。

我想這樣做的方法是使用一個For /下一條語句,而現在它將工作這將是我會用它在電腦上一個艱苦的過程。

的代碼我想使用看起來像這樣的:

For intCounter=0 to Whatever Number is the last number of the array 

    If currentfield.contains(array(intCounter)) Then 

     Open StreamWriter(File directory & array(intcounter) & ".txt") 

     Streamwriter.Writeline(currentfield) 

    End IF 

是否有這樣做,比如在該行引用的第二個「列」,類似於VBA中使用的語法的一個更好的辦法爲excel。

Name=Cells(1,2).Value 
+0

在[這個問題](http://stackoverflow.com/questions/9185403/parsing-a-tab-delimited-text-file-with-vb-net)看看有關分析製表符分隔文本文件。它建議使用[TextFieldParser](https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.textfieldparser.aspx#Y0),我建議使用相同的。 –

回答

0

所以,雖然它沒有使用數組來搜索文件,但我最終做的工作同樣如此。感謝@Martin鞋底,我最終使用了拆分方法。

這裏是我想出了:

Sub Main() 
    Dim intCount As Integer = 1 
    Dim words As String 
    Dim split As String() 
    Using MyReader As New Microsoft.VisualBasic. 
        FileIO.TextFieldParser(
         "I:\Games, Events, & Promotions\FRP\Back End\Approved.txt") 
     MyReader.TextFieldType = FileIO.FieldType.Delimited 
     MyReader.SetDelimiters(",") 
     Dim currentRow As String() 
     While Not MyReader.EndOfData 
      Try 
       currentRow = MyReader.ReadFields() 
       Dim currentField As String 
       For Each currentField In currentRow 

        words = currentField 
        split = words.Split(New [Char]() {CChar(vbTab)}) 

        For Each s As String In split 
         If intCount = 2 Then 
          Dim file As System.IO.StreamWriter 
          file = My.Computer.FileSystem.OpenTextFileWriter("I:\Games, Events, & Promotions\FRP\Back End\" & s & ".txt", True) 
          file.WriteLine(currentField) 
          file.Close() 
         End If 
         intCount = intCount + 1 
        Next s 
        intCount = 1 
       Next 
      Catch ex As Microsoft.VisualBasic. 
       FileIO.MalformedLineException 
       MsgBox("Line " & ex.Message & 
    "is not valid and will be skipped.") 
      End Try 
     End While 
    End Using 

End Sub 'Main 

感謝您的建議傢伙。

對於現在的拆分方法將工作所需。

0

如果你能保證線路將僅使用製表符作爲字段分隔,你可以做一些事情沿着這條:

  1. 打開流以讀取文本
  2. 打開一個流寫作文
  3. 讀取文本行的
  4. 使用拆分法進線打入字段的數組
  5. 如果數組中的第二個元素是你的標記值,寫原線至筆者
  6. 重複自己,直到你已經達到文件的末尾(的ReadLine將返回Nothing或null對於那些C#民俗)。
  7. 關閉並處理您的流對象。

如果您不確定格式,您需要按照前面的註釋中提到的那樣使用TextFieldParser。