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

南笙酒味 提交于 2019-11-27 09:27:25

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() );
Rajesh

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());

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());

one of the trick is file transaction. first you read the file up to the line you want to add text but while reading keep saving the read lines in a separate file for example tmp.txt and then add your desired text to the tmp.txt (at the end of the file) after that continue the reading from the source file till the end. then replace the tmp.txt with the source file. at the end you got file with added text in the middle :)

If you know the line index use readLine until you reach that line and write under it. If you know exactly he text of that line do the same but compare the text returned from readLine with the text that you are searching for and then write under that line.

Or you can search for the index of a specified string and writ after it using th escape sequence \n.

As others mentioned, there is no way around rewriting the file after the point of the newly inserted text if you must stick with a simple text file. Depending on your requirements, though, it might be possible to speed up the finding of location to start writing. If you knew that you needed to add data after line N, then you could maintain a separate "index" of the offsets of line numbers. That would allow you to seek directly to the necessary location to start reading/writing.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!