Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert characters to a file using C#

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.

like image 903
Gulzar Nazim Avatar asked Sep 19 '08 00:09

Gulzar Nazim


1 Answers

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);
}
like image 99
Scott Marlowe Avatar answered Oct 07 '22 23:10

Scott Marlowe