Solved

# Add line number to text file

Posted on 2013-06-17
Medium Priority
579 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
Question by:rflorencio
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• Learn & ask questions
2 Comments

LVL 42

Assisted Solution

sedgwick earned 600 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)

0

LVL 75

Accepted Solution

käµfm³d   👽 earned 1400 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


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

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor (https://www.adremsoft.com/). Top Charts is a view in which you can set seve…
In this video, Percona Solution Engineer Dimitri Vanoverbeke discusses why you want to use at least three nodes in a database cluster. To discuss how Percona Consulting can help with your design and architecture needs for your database and infras…
###### Suggested Courses
Course of the Month7 days, 23 hours left to enroll

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

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