Insert line at specific location in txt using .net

Currently, the process that I use to insert a line into a text file is to read the file and change it when I write the file again, which seems to be all doing it.

Since .net has such a diverse library, I was wondering if there was a special command to insert a line into a specific line in a txt file.

I would suggest that 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
+3
source share
2 answers

No, in .NET there is nothing special.

You can do this very simply if you enjoyed reading all the lines of text in:

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

, , . , , .

+8

, insert,

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

All Articles