我在将编辑过的数据保存到原始文件时遇到了一些问题... 我想将我的字符串从textBox1保存到它加载的文件中。
这是我的“加载”功能:
public static string getItemName(int index)
{
FileStream str = File.OpenRead(Directory.GetCurrentDirectory() + ybi);
BinaryReader breader = new BinaryReader(str);
breader.BaseStream.Position = itemSectionStart;
byte[] itemSection = breader.ReadBytes(itemSectionEnd);
string itemName = BitConverter.ToString(itemSection, 808 * index + 7, 64).Replace("00", "").Replace("-", "");
return hex2ascii(itemName);
}
这是我的“保存”功能:
public static bool setItemName(int index, string _FileName, byte[] _ByteArray)
{
try
{
System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
_FileStream.Write(_ByteArray, 808 * index + 7, _ByteArray.Length);
_FileStream.Close();
return true;
}
catch (Exception _Exception)
{
MessageBox.Show(Convert.ToString(_Exception.Message));
}
return false;
}
现在,我认为这是问题所在,从我的HEX String转换为ByteArray ......
private byte[] HexStringToByteArray(string hexString)
{
int hexStringLength = hexString.Length;
byte[] b = new byte[hexStringLength / 2];
for (int i = 0; i < hexStringLength; i += 2)
{
int topChar = (hexString[i] > 0x40 ? hexString[i] - 0x37 : hexString[i] - 0x30) << 4;
int bottomChar = hexString[i + 1] > 0x40 ? hexString[i + 1] - 0x37 : hexString[i + 1] - 0x30;
b[i / 2] = Convert.ToByte(topChar + bottomChar);
}
return b;
}
private void button2_Click(object sender, EventArgs e)
{
int index = listBox1.SelectedIndex;
string hex = "";
foreach (char c in textBox1.Text)
{
int tmp = c;
hex += String.Format("{0:x2}", (uint)System.Convert.ToUInt32(tmp.ToString()));
}
writeValuePositions.setItemName(index, save_FileName, HexStringToByteArray(hex.ToUpper()));
}
发送到writeValuePositions.setItemName的byteArray不对我认为......我得到了这个例外
---------------------------
---------------------------
Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.
---------------------------
OK
---------------------------
答案 0 :(得分:0)
我在setItemName中看到了您的行的潜在问题:
_FileStream.Write(_ByteArray, 808 * index + 7, _ByteArray.Length);
第二个参数是起始偏移量,第三个参数是要写入的字符总数。看起来你正在编写808 * index + 7个字节通过数组的末尾。如果要写出数组的末尾,请从计数中减去偏移量。
答案 1 :(得分:0)
试试这个:
private void button2_Click(object sender, EventArgs e)
{
writeValuePositions.setItemName(index, save_FileName, HexStringToByteArray(textBox1.Text);
}
private byte[] HexStringToByteArray(string hexString)
{
if (String.IsNullOrEmpty(hexString) || hexString.Length % 2 != 0)
{
throw new ArgumentException("Invalid parameter.");
}
byte[] array = new byte[hexString.Length / 2];
for (int i = 0; i < hexString.Length / 2; i++)
{
array[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
}
return array;
}
请记住John Saunders在评论中建议你的内容。