Reputation: 13
I have a folder that contains about 100 txt files with information in each file.
I'm trying to figure out how to loop through each file in the folder, and add the text to a string.
I've pulled this off MSDN's site, but it doesn't seem to read "each" file but just one.
Any ideas on how to read each file in a folder and add the text to a string? thanks
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)
This just gives me the text they created and not anything from the txt files.
Upvotes: 0
Views: 3650
Reputation: 224952
What you'll want to do is loop through the files using the DirectoryInfo.GetFiles()
method. Here's an example, which also uses a StringBuilder
for better performance:
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()
Upvotes: 1