title: Replace Hex String in File
body: <p>After banging my head on it for hours, I am at my wits end. I have a hex string in a file that is "68 39 30 00 00". The "39 30" is the decimal value "12345" which I am wanting to replace, and the "68" and "00 00" are just to ensure there is a single match.</p>
  
  <p>I want to pass in a new decimal value such as "12346", and replace the existing value in the file. I have tried converting everything back and fourth between hex, byte arrays, and so on and feel it has to be much simpler than I am making it out to be.</p>
  
  <pre><code>static void Main(string[] args)
  {
      // Original Byte string to find and Replace "12345"
      byte[] original = new byte[] { 68, 39, 30, 00, 00 };
  
      int newPort = Convert.ToInt32("12346");
      string hexValue = newPort.ToString("X2");
      byte[] byteValue = StringToByteArray(hexValue);
  
      // Build Byte Array of the port to replace with. Starts with /x68 and ends with /x00/x00
      byte[] preByte = new byte[] { byte.Parse("68", System.Globalization.NumberStyles.HexNumber) };
      byte[] portByte = byteValue;
      byte[] endByte = new byte[] { byte.Parse("00", System.Globalization.NumberStyles.HexNumber), byte.Parse("00", System.Globalization.NumberStyles.HexNumber) };
  
      byte[] replace = new byte[preByte.Length + portByte.Length + endByte.Length];
  
      preByte.CopyTo(replace, 0);
      portByte.CopyTo(replace, preByte.Length);
      endByte.CopyTo(replace, (preByte.Length + portByte.Length));
  
      Patch("Server.exe", "Server1.exe", original, replace);
  }
  
  static private byte[] StringToByteArray(string hex)
  {
      return Enumerable.Range(0, hex.Length)
                       .Where(x =&gt; x % 2 == 0)
                       .Select(x =&gt; Convert.ToByte(hex.Substring(x, 2), 16))
                       .ToArray();
  }
  </code></pre>