david hol david hol - 1 month ago 8
C# Question

How to promote a byte by specific value?

So i have this file that i am opening:

static void Encrypt(string fileName)
{
using (FileStream stream = File.OpenRead(fileName))
{
using (BinaryReader reader = new BinaryReader(stream))
{
for (int i = 0; i < stream.Length; i++)
{
byte b = reader.ReadByte();
byte newByte = (byte(b + 5))
}
}
}
}


And i want to add specific value to each byte in my file and save it.

Answer

So just store the new bytes in a collection and save them after reading whole file.

var newBytes = new List<byte>();
...
for (int i = 0; i < stream.Length; i++)
{
    byte b = reader.ReadByte();
    newBytes.Add(b + 5);
}
...

File.WriteAllBytes(filePath, newBytes.ToArray());