2012-01-20 67 views
0

我有一個文件夾,其中包含約100個txt文件,每個文件中包含信息。需要循環遍歷一個文件夾,並將每個文本文件讀入一個字符串

我想弄清楚如何遍歷文件夾中的每個文件,並將文本添加到字符串。

我從MSDN的網站上取消了這個功能,但它似乎並沒有讀取「每個」文件,只有一個。

關於如何讀取文件夾中的每個文件並將文本添加到字符串的任何想法?謝謝

Dim path As String = "c:\temp\MyTest.txt" 

    ' This text is added only once to the file. 
    If File.Exists(path) = False Then 

     ' Create a file to write to. 
     Dim createText As String = "Hello and Welcome" + Environment.NewLine 
     File.WriteAllText(path, createText) 
    End If 

    ' This text is always added, making the file longer over time 
    ' if it is not deleted. 
    Dim appendText As String = "This is extra text" + Environment.NewLine 
    File.AppendAllText(path, appendText) 

    ' Open the file to read from. 
    Dim readText As String = File.ReadAllText(path) 
    RichTextBox1.Text = (readText) 

這只是給我他們創建的文本,而不是從txt文件中的任何東西。

回答

1

你想要做的是使用DirectoryInfo.GetFiles() method循環遍歷文件。下面是一個例子,它也使用StringBuilder獲得更好的性能:

Dim fileContents As New System.Text.StringBuilder() 

For Each f As FileInfo In New DirectoryInfo("C:\MyFolder").GetFiles("*.txt") ' Specify a file pattern here 
    fileContents.Append(File.ReadAllText(f.FullName)) 
Next 

' Now you can access all the contents using fileContents.ToString() 
+0

太棒了... ...就像一個魅力.... –

相關問題