How to insert characters to a file using C#

2020-01-26 10:43发布

I have a huge file, where I have to insert certain characters at a specific location. What is the easiest way to do that in C# without rewriting the whole file again.

10条回答
SAY GOODBYE
2楼-- · 2020-01-26 11:11

It may be "possible" depending on how the filesystem stores files to quickly insert (ie, add additional) bytes in the middle. If it is remotely possible it may only be feasible to do so a full block at a time, and only by either doing low level modification of the filesystem itself or by using a filesystem specific interface.

Filesystems are not generally designed for this operation. If you need to quickly do inserts you really need a more general database.

Depending on your application a middle ground would be to bunch your inserts together, so you only do one rewrite of the file rather than twenty.

查看更多
看我几分像从前
3楼-- · 2020-01-26 11:12

You can use random access to write to specific locations of a file, but you won't be able to do it in text format, you'll have to work with bytes directly.

查看更多
The star\"
4楼-- · 2020-01-26 11:12

If you know the specific location to which you want to write the new data, use the BinaryWriter class:

using (BinaryWriter bw = new BinaryWriter (File.Open (strFile, FileMode.Open)))
{
    string strNewData = "this is some new data";
    byte[] byteNewData = new byte[strNewData.Length];

    // copy contents of string to byte array
    for (var i = 0; i < strNewData.Length; i++)
    {
        byteNewData[i] = Convert.ToByte (strNewData[i]);
    }

    // write new data to file
    bw.Seek (15, SeekOrigin.Begin);  // seek to position 15
    bw.Write (byteNewData, 0, byteNewData.Length);
}
查看更多
可以哭但决不认输i
5楼-- · 2020-01-26 11:18

Depending on the scope of your project, you may want to decide to insert each line of text with your file in a table datastructure. Sort of like a database table, that way you can insert to a specific location at any given moment, and not have to read-in, modify, and output the entire text file each time. This is given the fact that your data is "huge" as you put it. You would still recreate the file, but at least you create a scalable solution in this manner.

查看更多
登录 后发表回答