Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a Line to the Middle of a File with .NET

Hello I am working on something, and I need to be able to be able to add text into a .txt file. Although I have this completed I have a small problem. I need to write the string in the middle of the file more or less. Example:

Hello my name is Brandon,
I hope someone can help, //I want the string under this line.
Thank you.

Hopefully someone can help with a solution.

Edit Alright thanks guys, I'll try to figure it out, probably going to just rewrite the whole file. Ok well the program I am making is related to the hosts file, and not everyone has the same hosts file, so I was wondering if there is a way to read their hosts file, and copy all of it, while adding the string to it?

like image 202
Brandon Avatar asked Jan 11 '10 19:01

Brandon


People also ask

How to insert a new line in c#?

By using: \n – It prints new line. By using: \x0A or \xA (ASCII literal of \n) – It prints new line.

How write and append to a file in C#?

AppendText() Method in C# with Examples. File. AppendText() is an inbuilt File class method which is used to create a StreamWriter that appends UTF-8 encoded text to an existing file else it creates a new file if the specified file does not exist.


3 Answers

With regular files there's no way around it - you must read the text that follows the line you wish to append after, overwrite the file, and then append the original trailing text.

Think of files on disk as arrays - if you want to insert some items into the middle of an array, you need to shift all of the following items down to make room. The difference is that .NET offers convenience methods for arrays and Lists that make this easy to do. The file I/O APIs offer no such convenience methods, as far as I'm aware.

When you know in advance you need to insert in the middle of a file, it is often easier to simply write a new file with the altered content, and then perform a rename. If the file is small enough to read into memory, you can do this quite easily with some LINQ:

var allLines = File.ReadAllLines( filename ).ToList();
allLines.Insert( insertPos, "This is a new line..." );
File.WriteAllLines( filename, allLines.ToArray() );
like image 182
LBushkin Avatar answered Sep 20 '22 10:09

LBushkin


This is the best method to insert a text in middle of the textfile.

 string[] full_file = File.ReadAllLines("test.txt");
 List<string> l = new List<string>();
 l.AddRange(full_file);
 l.Insert(20, "Inserted String"); 
 File.WriteAllLines("test.txt", l.ToArray());
like image 4
Rajesh Avatar answered Sep 22 '22 10:09

Rajesh


Check out File.ReadAllLines(). Probably the easiest way.

     string[] full_file = File.ReadAllLines("test.txt");
     List<string> l = new List<string>();
     l.AddRange(full_file);
     l.Insert(20, "Inserted String");
     File.WriteAllLines("test.txt", l.ToArray());
like image 2
SwDevMan81 Avatar answered Sep 24 '22 10:09

SwDevMan81