Aeropher
Aeropher

Reputation: 117

Inserting a Line at a specific place in a txt using .net

The process I currently use to insert a string into a text file is to read the file and modify it as I write the file out again which seems to be how everyone is doing it.

Since .net has such a diverse library I was wondering if there was a specific command for inserting a string at a specific line in a txt file.

I would imagine it would look something like this:

dim file as file
file.open("filePath")

file.insert(string, location) 'this isn't actually an option, I tried

Upvotes: 3

Views: 1946

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500805

No, there's nothing specifically to do that in .NET.

You can do it very simply if you're happy to read all the lines of text in:

var lines = File.ReadAllLines("file.txt").ToList();
lines.Insert(location, text);
File.WriteAllLines("file.txt", lines);

It would be more efficient in terms of memory to write code to copy a line at a time, inserting the new line at the right point while you copy, but that would be more work. If you know your file will be small, I'd go for the above.

Upvotes: 8

Alex Peck
Alex Peck

Reputation: 4711

You could simply read all the text into a string, then use the string insert method, e.g.

File.WriteAllText("file.txt", File.ReadAllText("file.txt").Insert(startIndex, "value"));

Upvotes: 1

Related Questions