2012-01-20 5 views
0

各ファイルの情報を含む約100個のtxtファイルを含むフォルダーがあります。フォルダーをループして各テキストファイルを文字列に読み込む必要があります

私はフォルダ内の各ファイルをループする方法を理解し、文字列にテキストを追加しようとしています。

私はこれをMSDNのサイトから削除しましたが、「各ファイル」を読むのではなく、1つのファイルだけを読むようです。

フォルダ内の各ファイルを読み込んで文字列に追加する方法に関するアイデアはありますか?ありがとう

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

素晴らしい...魅力的な作品です –

関連する問題