Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.IO;
- using System.Text;
- class HexReplace
- {
- static void Main()
- {
- Console.WriteLine("Enter the path to the .ucas file:");
- string filePath = Console.ReadLine();
- Console.WriteLine("Enter the hex value to replace:");
- string hexToReplace = Console.ReadLine();
- Console.WriteLine("Enter the new hex value:");
- string newHexValue = Console.ReadLine();
- if (hexToReplace.Length != newHexValue.Length)
- {
- Console.WriteLine("Error: The lengths of the hex values should be the same.");
- return;
- }
- try
- {
- // Read the content of the file
- string fileContent = File.ReadAllText(filePath);
- // Search and replace the hex value
- string updatedContent = ReplaceHexValue(fileContent, hexToReplace, newHexValue);
- // Write the updated content back to the file
- File.WriteAllText(filePath, updatedContent);
- Console.WriteLine("Hex value replaced successfully.");
- }
- catch (Exception ex)
- {
- Console.WriteLine($"An error occurred: {ex.Message}");
- }
- }
- static string ReplaceHexValue(string input, string hexToReplace, string newHexValue)
- {
- // Convert hex strings to byte arrays
- byte[] hexBytesToReplace = StringToByteArray(hexToReplace);
- byte[] newHexBytes = StringToByteArray(newHexValue);
- // Replace the hex value in the input string
- int index = input.IndexOf(hexBytesToReplace, StringComparison.OrdinalIgnoreCase);
- while (index != -1)
- {
- input = input.Remove(index, hexBytesToReplace.Length);
- input = input.Insert(index, ByteArrayToString(newHexBytes));
- index = input.IndexOf(hexBytesToReplace, index + newHexBytes.Length, StringComparison.OrdinalIgnoreCase);
- }
- return input;
- }
- static byte[] StringToByteArray(string hex)
- {
- return Enumerable.Range(0, hex.Length)
- .Where(x => x % 2 == 0)
- .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
- .ToArray();
- }
- static string ByteArrayToString(byte[] byteArray)
- {
- StringBuilder hex = new StringBuilder(byteArray.Length * 2);
- foreach (byte b in byteArray)
- {
- hex.AppendFormat("{0:x2}", b);
- }
- return hex.ToString();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement