2012-01-20 71 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

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

相关问题