Rgm1998
Rgm1998

Reputation: 13

How I can insert bytes in a FileStream in C#

If I have a file with this data:

01 02 03 04 05 06 07 08 09 0A

When I try to insert byte FF, for example, between 01 and 02, the new file will be something like that:

01 FF 03 04 05 06 07 08 09 0A

But I'd like to insert that byte instead of replace one. How can I do it?

01 FF 02 03 04 05 06 07 08 09 0A

Upvotes: 1

Views: 2376

Answers (2)

HackerMan
HackerMan

Reputation: 914

 int index=1;

        byte item=01;
            List<byte> by = new List<byte>();
            string path = "Path here";
            Byte[] b = File.ReadAllBytes(path);

            by = b.ToList();
            by.Insert(index, item);

Upvotes: -2

Fredou
Fredou

Reputation: 20118

  1. you need to create a new array with the proper size
  2. insert all bytes before 02 in the same order
  3. insert the new bytes
  4. you have to shift all bytes, from 02, to the right

so mostly this

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var insertInPos = 1;

            var inBytes = new byte[] {01 ,02 ,03, 04, 05, 06, 07, 08, 09, 0x0A };

            var insertBytes = new byte[] {0xFF, 0xDD};

            var newBytes = InsertBytes(inBytes, insertBytes, insertInPos);
        }

        public static byte[] InsertBytes(byte[] inBytes, byte[] insertBytes, int insertInPos)
        {
            var insertLen = insertBytes.Length - 1;

            var outBytes = new byte[inBytes.Length + insertLen + 1];
            var outLen = outBytes.Length - 1;

            for (int i = 0, j = 0; i < outLen; ++i)
            {
                if (i < insertInPos)
                {
                    outBytes[i] = inBytes[i];
                }
                else if (i == insertInPos)
                {
                    while (j <= insertLen)
                    {
                        outBytes[i + j] = insertBytes[j++];
                    }
                }
                else
                {
                    outBytes[i + insertLen] = inBytes[i - insertLen];
                }
            }

            return outBytes;
        }
    }
}

Upvotes: 3

Related Questions