i want to add some text at the begining of every line in a text file.
i'm only able to append text to the file

        Imports System.IO

        Module Module1
Sub Main()
    ' Append the first line of text to a new file.
    Using writer As StreamWriter =
        New StreamWriter("C:\append.txt", True)

        writer.WriteLine("First line appended; rtp")
    End Using

    ' Append the second line.
    Using writer As StreamWriter =
        New StreamWriter("C:\append.txt", True)

        writer.WriteLine("Second line appended; 2")
    End Using
End Sub
    End Module

In psuedocode to do this we read a file line by line then insert the text on each line then write the line to another file.
At the end of the file we close both files. Optionally you could delete the source and rename the edited file to the source's name.

Consider reading all the lines at the beginning and, then, prepending the line number, like in:

        Try
            Dim vLines() As String = IO.File.ReadAllLines("Append.txt")
            Using sw As New StreamWriter("Append.txt")
                For i As Int32 = 0 To vLines.Length - 1
                    sw.Write(String.Format("Line #{0:0000} ", i) + vLines(i) + vbCrLf)
                Next
            End Using
        Catch ex As Exception

        End Try
commented: I'd like to try that on a 4+ terabyte file just to see what vb.net would do. There are reasons to code this with input and output files. +15

That seems like the type of task more suited to a script than an app. If you copy the following into a file named prefix.vbs you can do what you requested.

set fso = CreateObject("Scripting.FileSystemObject")

if wscript.arguments.unnamed.count <> 2 then
    Wscript.Echo "prefix <filename> ""string"""
    Wscript.Quit
end if

infile  = wscript.arguments.unnamed(0)
outfile = infile & ".pre"
prefix  = wscript.arguments.unnamed(1)

if not fso.FileExists(infile) then
    Wscript.Echo "File '" & infile & "' not found"
    Wscript.Quit
end if

set fi = fso.OpenTextFile(infile)
set fo = fso.OpenTextFile(outfile,2,True)  '2=write True=create if needed

do while not fi.AtEndOfStream
    line = fi.ReadLine
    fo.WriteLine prefix & line
loop

fi.Close
fo.Close

It's a lot less complicated than the equivalent code in vb.Net. The output goes to the file <yourfile>.pre. For example, if you feed it myfile.txt you will get myfile.txt.pre. Once you verify the results you can rename it.

@rproffitt: If the file is large and assuming we can buffer a first bunch of lines so that streamreader and streamwriter will never overlap:

        Try
            Dim path As String = "Append.txt"
            Using fs As New FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
                Dim sr As New StreamReader(fs)
                Dim sw As New StreamWriter(fs)
                Dim lineNum As Int32 = 1
                Dim fileLen As Long = fs.Length
                Dim linesToBuffer As Int32 = 3
                Dim currBufferLine As Int32 = 0
                Dim vBuffer(linesToBuffer - 1) As String
                Dim EndofBuffer As Int32 = -1
                Dim rdPos As Long = 0
                Dim wrPos As Long = 0
                For i = 0 To vBuffer.Length - 1
                    vBuffer(i) = sr.ReadLine
                Next
                rdPos = fs.Position
                Do
                    fs.Seek(wrPos, SeekOrigin.Begin)
                    sw.WriteLine(String.Format("Line #{0:0000000} ", lineNum) + vBuffer(currBufferLine))
                    wrPos = fs.Position 
                    ' if wrPos >= rdPos signifies buffer too small'
                    If rdPos < fileLen Then
                        fs.Seek(rdPos, SeekOrigin.Begin)
                        vBuffer(currBufferLine) = sr.ReadLine
                        rdPos += vBuffer(currBufferLine).Length + 2
                        lineNum += 1
                    Else
                        If EndofBuffer = -1 Then
                            sr.Close()
                            EndofBuffer = linesToBuffer
                        End If
                        EndofBuffer -= 1
                        If EndofBuffer < 0 Then Exit Do
                    End If
                    currBufferLine = (currBufferLine + 1) Mod linesToBuffer
                Loop
                sw.Close()
            End Using
        Catch ex As Exception

        End Try
commented: Now throw this a zero byte file. Excellent examples where something simple grows and grows to cover every condition. +0

This sounds like a very bad idea for two reasons:

  1. The code is overly complex (tricky) for the task and I believe that with very few exceptions, clear code is always preferable to tricky code.
  2. If anything breaks the process midway through the original file is corrupted.

Having said that, I admit that it was an interesting and clever approach.

commented: In the news, MySpace server transition loses over a decade of uploads. "My code is quite the trick." +15

For some reason I don' t know, yesterday the code was working and today it fails. So, I've rewritten the code and it is:

Sub Main()
    Try
        prependTextToAllLines("Append.txt")
    Catch ex As Exception
        Console.WriteLine(ex.ToString)
        Console.ReadLine()
    End Try

End Sub
Sub prependTextToAllLines(path As String)
    Dim bRet As Boolean = False
    Dim fs As FileStream = Nothing
    Dim fsw As FileStream = Nothing
    Dim sr As StreamReader = Nothing
    Dim sw As StreamWriter = Nothing
    Try
        fsw = New FileStream(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite)
        sw = New StreamWriter(fsw)
        fs = New FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
        sr = New StreamReader(fs)
        Dim lineNum As Int32 = 1
        Dim fileLen As Long = fs.Length
        Dim currBufferLine As Int32 = 0
        Dim EndofBuffer As Int32 = -1
        Dim rdPos As Long = 0
        Dim wrPos As Long = 0
        Do
            Dim sCurrLn As String = sr.ReadLine
            Dim sPrepend As String = String.Format("Line #{0:0000000} ", lineNum)
            lineNum += 1
            sw.WriteLine(sPrepend + sCurrLn)
        Loop While Not sr.EndOfStream
        sr.Close()
        sw.Close()
        bRet = True
    Catch ex As Exception
    End Try
End Sub

Sorry for the inconvient. There were extra lines not needed.

    Sub Main()
        Try
            prependTextToAllLines("Append.txt")
            Console.Write("Process succeeded. Press Enter key to exit.")
            Console.ReadLine()
        Catch ex As Exception
            Console.WriteLine(ex.ToString)
            Console.ReadLine()
        End Try

    End Sub
    Sub prependTextToAllLines(path As String)
        Try
            Dim fsw As New FileStream(path, FileMode.Open, FileAccess.Write, FileShare.Read)
            Dim sw As New StreamWriter(fsw)
            Dim fs As New FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
            Dim sr As New StreamReader(fs)
            Dim lineNum As Int32 = 1
            Do
                Dim sCurrLn As String = sr.ReadLine
                Dim sPrepend As String = String.Format("Line #{0:0000000} ", lineNum)
                lineNum += 1
                sw.WriteLine(sPrepend + sCurrLn)
            Loop While Not sr.EndOfStream
            sr.Close()
            sw.Close()
        Catch ex As Exception
            Throw ex
        End Try
    End Sub
End Module
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.