Option Strict On

Imports System.IO

Module FileMerger

    Sub Main(ByVal Args() As String)
        Try
            If Args.Length <= 0 Then
                Console.WriteLine("FileMerger.exe FromFilePath IntoFilePath LineNumber NewFilePath")
                Exit Sub
            End If
            Dim FromFile As String = Args(0)

            Dim ToFile As String = Args(1)

            Dim LineNum As Integer = CInt(Args(2))

            Dim NewFile As String = Args(3)

            Dim FromContents As New ArrayList
            StringParse(FromFile, FromContents)

            Dim ToContents As New ArrayList
            StringParse(ToFile, ToContents)

            If LineNum < 0 Then
                LineNum = Math.Abs(LineNum) - 1
                ToContents.RemoveAt(LineNum)
            End If

            For x As Integer = 0 To FromContents.Count - 1
                ToContents.Insert(LineNum + x, FromContents(x))
            Next

            Dim objWriter As New StreamWriter(NewFile)
            For x As Integer = 0 To ToContents.Count - 1
                objWriter.WriteLine(ToContents(x))
            Next
            objWriter.Flush()
            objWriter.Close()
            Console.WriteLine("Files Merged.")
        Catch Ex As Exception
            Console.WriteLine(Ex)
        End Try

    End Sub

    Private Sub StringParse(ByVal FilePath As String, ByVal StrContents As ArrayList)
        Dim objReader As StreamReader
        objReader = New StreamReader(FilePath)
        While objReader.Peek <> -1
            StrContents.Add(objReader.ReadLine)
        End While
        objReader.Close()
    End Sub
End Module
