Thursday, March 10, 2011

Code to split a large text file into smaller chunks of file

This code is in VB.NET:


Private Sub btnBreak_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBreak.Click
        Dim tsInput As StreamReader
        Dim tsOp As StreamWriter
        Dim fi As FileInfo
        Dim iLineCtr, iCntPerFile, fileCnt As Integer
        Dim strLine, strFileNameGen As String
        Dim opFile As String
        Try
            tsInput = New StreamReader(txtFileName.Text)
            fi = New FileInfo(txtFileName.Text)
            iCntPerFile = Convert.ToInt32(txtlineCount.Text)
            fileCnt = 1
            strFileNameGen = txtOutput.Text + "\" + fi.Name.Remove(fi.Name.Length - 4)
            Do
                opFile = strFileNameGen + fileCnt.ToString("0000") + fi.Name.Substring(fi.Name.Length - 4)

                tsOp = New StreamWriter(opFile)
                For iLineCtr = 1 To iCntPerFile
                    If (Not tsInput.EndOfStream) Then
                        strLine = tsInput.ReadLine()
                        tsOp.WriteLine(strLine)
                    End If
                Next
                tsOp.Close()
                tsOp = Nothing
                fileCnt = fileCnt + 1
            Loop While (Not tsInput.EndOfStream)

        Catch ex As Exception
            MessageBox.Show(ex.Message.Trim())
        End Try

    End Sub




No comments: