Solved

Add line number to text file

Posted on 2013-06-17
2
520 Views
Last Modified: 2013-06-17
I have a text file without line numbers and i need to insert a line number for each file.

Text File

aaaaaa
bbbbb
cccccc
.....

With line numbers

1 aaaaaa
2 bbbbb
3 cccccc
0
Comment
Question by:rflorencio
2 Comments
 
LVL 42

Assisted Solution

by:sedgwick
sedgwick earned 150 total points
ID: 39253353
        Dim lines = File.ReadAllLines("c:\temp\1.txt")
        Dim list As List(Of String) = New List(Of String)
        For Each l In lines
            list.Add((list.Count + 1).ToString & " " & l)
        Next

        File.WriteAllLines("c:\temp\1.txt", list.ToArray)

Open in new window

0
 
LVL 74

Accepted Solution

by:
käµfm³d   👽 earned 350 total points
ID: 39253398
Depending on how large your files are, it may be more prudent to use StreamReaders and StreamWriters.

e.g.

Imports System.IO

...

Using reader As New StreamReader("C:\path\to\your\file.txt")
    Using writer As New StreamWriter("C:\path\to\temp\file.txt")
        Dim i As Integer = 1

        While Not reader.AtEndOfStream
            writer.WriteLine("{0} {1}", i.ToString(), reader.ReadLine())
            i += 1
        End While
    End Using
End Using

Open in new window


You can move (i.e. rename) the temp file to the original file to effectively overwrite the old file.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

This article explains how to create and use a custom WaterMark textbox class.  The custom WaterMark textbox class allows you to set the WaterMark Background Color and WaterMark text at design time.   IMAGE OF WATERMARKS STEPS Create VB …
Microsoft Reports are based on a report definition, which is an XML file that describes data and layout for the report, with a different extension. You can create a client-side report definition language (*.rdlc) file with Visual Studio, and build g…
This video discusses moving either the default database or any database to a new volume.
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now