添加与.NET中的文件中的行到中东中东、文件、NET

2023-09-02 10:51:49 作者:っ该留的留

您好我工作的事情,我需要能够能够添加文本.txt文件。虽然我已经完成了这个我有一个小问题。我需要编写中的字符串的文件或多或少中间。例如:

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.

修改好的谢谢你们,我会尽力搞清楚,可能将只是重写整个文件。好吧好吧,我做节目是关系到hosts文件,而不是每个人都有相同的hosts文件,所以我在想,如果有一种方法来阅读他们的hosts文件,并复制它,同时加入了串吧?

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?

推荐答案

随着常规文件有没有办法解决它 - 你必须阅读如下您希望在追加行的文本,覆盖文件,然后追加原来尾随文本。

想在磁盘上,阵列的文件 - 如果要插入一些项目到一个数组的中间,你需要转移所有的下列项目下以腾出空间。不同的是,.NET提供了便利的方法数组和列表,使这个很容易做到。该文件I / O API提供了没有这样的便利的方法,据我所知。

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.

当你提前知道你需要在文件中间插入,它往往容易简单地写与改变的内容的新文件,然后进行重命名。 如果该文件是足够小,以读入内存,你可以用一些LINQ做到这一点很容易:

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