Introduction
This application helps you merge two text files into one. You can either select individual files or select a folder to merge all of the text files in it. The File / Folder dialog box helps to select files.
Using the code
Text files can be merged using basic file operations. Using the StreamReader
class, files from the list box (LstFiles
) can be opened, read to a temporary string (temp
) and appended to a new file. The new file name is typed into SaveFileDialog
.
Private Sub SaveFileDialog1_FileOk(ByVal sender As Object, _
ByVal e As System.ComponentModel.CancelEventArgs) _
Handles SaveFileDialog1.FileOk
Dim FileReader As StreamReader
Dim i As Integer = 0
Dim temp As String
For i = 0 To LstFiles.Items.Count - 1
FileReader = File.OpenText(LstFiles.Items.Item(i))
temp = FileReader.ReadToEnd
File.AppendAllText(SaveFileDialog1.FileName, temp)
Next
Dim prompt As String
prompt = String.Concat(lbl_NoOfFiles.Text, " files merged succesfully")
MsgBox(prompt, MsgBoxStyle.Information, "Merge")
LstFiles.Items.Clear()
lbl_NoOfFiles.Text = "0"
End Sub
All files in a folder can be selected by clicking on the Select Folder button. Filenames are stored in the files()
array by first using FolderBrowserDialog
and then adding the items of the array to the list box.
Private Sub BtnFolderMerge_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles BtnFolderMerge.Click
FolderBrowserDialog1.ShowDialog()
Dim files() As String
files = Directory.GetFiles(FolderBrowserDialog1.SelectedPath, "*.txt")
Dim i As Integer = 0
For i = 0 To files.Length - 1
LstFiles.Items.Add(files(i))
Next
Label2.Visible = True
lbl_NoOfFiles.Text = CStr(LstFiles.Items.Count)
lbl_NoOfFiles.Visible = True
End Sub
Points of interest
To filter the File dialog, a filter like this is helpful. This displays only files with the *.txt extension: OpenFileDialog1.Filter = "Text files (*.txt)|*.txt"
History
- Article first submitted on July 30th, 2007
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.