Home > Mobile >  C# BinaryWriter edit and write value from TextBox
C# BinaryWriter edit and write value from TextBox

Time:02-01

How I can get the offset position of the value which I get from the search byte array:

byte[] byteArray = File.ReadAllBytes(file);
string hex = BitConverter.ToString(byteArray);
                    

int index = hex.IndexOf("00-00-1F-00-0A-00-00-00-00-3C-00-00-00-");
if (index != -1)
{
    string value = hex.Substring(index   "00-00-1F-00-0A-00-00-00-00-3C-00-00-00-".Length, 5);
                       
    string speedLimit = value.Remove(2, 1);
    int decValue = Convert.ToInt32(speedLimit, 16);
    textBox3.Text = " "   decValue;                 
}

this is the code to search for 00-00-1F-00-0A-00-00-00-00-3C-00-00-00 And get the 4 byte which is 00F0 this value goes to textBox3 as int: 240

so how can I edit this value and write it back to the bin file?

please note that I wrote button when the button clicked,the new value of the textbox3 saved to the file

Thanks in advance.

CodePudding user response:

Example - note the position of the speed (240) were vague since it didn't match the payload, so I've just given an arbitrary example of that - you may need to tweak the offset relative to index, the size (Int16, etc), and the "endianness" (the order of the bytes - there are two different ways of writing the integer 240 as a 2-byte, 4-byte etc value - 0x00F0 vs 0xF000 - both are valid):

using System;
using System.IO;
using System.Buffers.Binary;

static class Program
{
    // this is not actually an array - the compiler optimizes it to a private data region
    static ReadOnlySpan<byte> Payload => new byte[] {
        0x00, 0x00, 0x1F, 0x00, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x00, 0x00, 0x00
    };
    static void Main()
    {
        const string PATH = "my.bin";
        // bad code to create a dummy file
        using (var file = File.Create(PATH))
        {
            Span<byte> tmp = new byte[1024];
            Random.Shared.NextBytes(tmp);
            Payload.CopyTo(tmp.Slice(999));
            // write the speed part
            tmp[999   Payload.Length] = 0x00;
            tmp[999   Payload.Length   1] = 0xF0;
            file.Write(tmp);
        }
        // OK, so: we now have a file with our expected payload at index 999
        // (unless the random gods give us one earlier!)

        UpdateSpeed(PATH, "my2.bin", 300);
    }
    private static void UpdateSpeed(string path, string newPath, short newValue)
    {
        byte[] allBytesRaw = File.ReadAllBytes(path); // note: this is not efficient at all
        Span<byte> allBytes = allBytesRaw; // this has no additional cost - just more convenient
        var index = allBytes.IndexOf(Payload);
        if (index < 0)
        {
            Console.WriteLine("not found");
        }
        else
        {
            Console.WriteLine($"found at index {index}");
            // read the two bytes big-endian that is immediately after this
            var speedChunk = allBytes.Slice(index   Payload.Length, 2);
            var oldValue = BinaryPrimitives.ReadInt16BigEndian(speedChunk); // 240, i.e. 0x00F0  in big-endian
            Console.WriteLine($"updating speed from {oldValue} to {newValue}");

            // change that value to 300
            BinaryPrimitives.WriteInt16BigEndian(speedChunk, newValue);
            // prove that we wrote what you expect (you can delete this line)
            Console.WriteLine(BitConverter.ToString(allBytesRaw, index   Payload.Length, 2));

            // rewrite the file (note: you *can* overwrite a file in-place, if
            // you use FileStream or MemoryMappedFile, but then it is harder
            // to use the IndexOf API; if the file is large, you may wish to
            // consider that)
            File.WriteAllBytes(newPath, allBytesRaw);
        }
    }
}

CodePudding user response:

you can write back the modified value by converting it back to a byte array and replacing the bytes in the original byteArray with the new values. For example:

if (index != -1)
{
    string value = hex.Substring(index   "00-00-1F-00-0A-00-00-00-00-3C-00-00-00-".Length, 5);
                   
    string speedLimit = value.Remove(2, 1);
    int decValue = Convert.ToInt32(speedLimit, 16);

    //Modify the decValue as needed
    decValue = 500;

    //Convert the modified decValue back to a byte array
    byte[] modifiedValue = BitConverter.GetBytes(decValue);

    //Replace the bytes in the original byteArray with the new values
    for (int i = 0; i < modifiedValue.Length; i  )
    {
        byteArray[index   "00-00-1F-00-0A-00-00-00-00-3C-00-00-00-".Length   i] = modifiedValue[I];
    }

    //Write the modified byteArray back to the file
    File.WriteAllBytes(file, byteArray);
}

Edit:

private void readButton_Click(object sender, EventArgs e)
{
    using (OpenFileDialog openFileDialog = new OpenFileDialog())
    {
        if (openFileDialog.ShowDialog() == DialogResult.OK)
        {
            byte[] byteArray = File.ReadAllBytes(openFileDialog.FileName);
            string hex = BitConverter.ToString(byteArray);
            int index = hex.IndexOf("00-00-1F-00-0A-00-00-00-00-3C-00-00-00-");
            if (index != -1)
            {
                 string value = hex.Substring(index   "00-00-1F-00-0A-00-00-00-00-3C-00-00-00-".Length, 5);

                 string speedLimit = value.Remove(2, 1);
                 int decValue = Convert.ToInt32(speedLimit, 16);
                 textBox3.Text = " "   decValue;
            }
        }
    }
}

private void writeButton_Click(object sender, EventArgs e)
{
    using (SaveFileDialog saveFileDialog = new SaveFileDialog())
    {
         if (saveFileDialog.ShowDialog() == DialogResult.OK)
         {
              int decValue = int.Parse(textBox3.Text);
              byte[] modifiedValue = BitConverter.GetBytes(decValue);

              //Replace the bytes in the original byteArray with the new values
              for (int i = 0; i < modifiedValue.Length; i  )
              {
                   byteArray[index   "00-00-1F-00-0A-00-00-00-00-3C-00-00-00-".Length   i] = modifiedValue[I];
              }

              //Write the modified byteArray back to the file
              File.WriteAllBytes(saveFileDialog.FileName, byteArray);
        }
    }
}
  •  Tags:  
  • c#
  • Related