help splitting text files
Posted on 2007-04-06
Good morning everyone, I am trying to create a small application, (VB.NET 2003) for breaking larger text files into smaller ones. The files need to be exactly 60,000 rows in length and the last file created amounts to the rest of the data. For example, the original file has 190,000 rows and is named tempfile. My desired result is the creation of 4 new files. The first three have 60,000 rows in each and the last file has the remaining rows of data, (10,000 rows). Also if possible I would like the files to keep the name of the original file and add a –part to the output files. In the above example the result was the creation of four new files. I would like them to be named tempfile-part1, tempfile-part2, tempfile-part3, tempfile-part4. Another thing is that I never know how many rows are going to be in the files and I know they have been as large as 3 million rows.
Please see the commented sections of my “attempted” source code below.
Thank you very much for taking the time to read this post and for any technical advice you can help me with,
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim inFile As String
Dim outFile As String
Dim openFileDialog1 As New OpenFileDialog
openFileDialog1.InitialDirectory = "c:\"
openFileDialog1.Filter = "txt files (*.txt|*.txt|All files(*.*)|*.*"
openFileDialog1.FilterIndex = 2
openFileDialog1.RestoreDirectory = True
If openFileDialog1.ShowDialog() = DialogResult.OK Then
inFile = openFileDialog1.FileName
outFile = Mid(inFile, 1, inFile.LastIndexOf("."))
'Need help creating the process of naming the files the OriginalFileName-part1, OriginalFileName-part2, etc
outFile += "-part1.txt"
Button1.Enabled = False
Dim startDT As DateTime = DateTime.Now
If (inFile.Length > 0) Then
If (outFile.Length > 0) Then
Dim stopDT As DateTime = DateTime.Now
Dim elapsedTS As TimeSpan = stopDT.Subtract(startDT)
Dim msg As String = elapsedTS.Hours & "h" & elapsedTS.Minutes & "m" & elapsedTS.Seconds & "s"
MessageBox.Show("File Complete! " & ControlChars.CrLf & ControlChars.CrLf & "Process Duration:" & ControlChars.CrLf & msg)
Button1.Enabled = True
MsgBox("No output file specified!")
MsgBox("No input file specified!")
Public Sub ConvertFiles(ByVal filein As String, ByVal fileout As String)
If (IO.File.Exists(filein)) Then
Dim sin As New IO.StreamReader(filein)
Dim sout As New IO.StreamWriter(fileout, False)
sout.AutoFlush = False ' output file is NOT updated after every WriteLine() call
Dim lineCounter As Integer
Dim items() As String
Dim readline As String = sin.ReadLine
While Not IsNothing(readline)
items = readline.Split(vbTab)
lineCounter = lineCounter + 1
If lineCounter Mod 60000 = 0 Then
'sout.write I am having trouble creating the files based on the row count
'sout.write the remaining data to the last file
readline = sin.ReadLine
Catch ex As Exception
MsgBox("Problem Occurred" & ex.Message)