Reputation: 13
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
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
Reputation: 20118
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