【发布时间】:2012-04-30 20:05:00
【问题描述】:
我在将编辑后的数据保存到原始文件时遇到了一些问题... 我想将我的字符串从 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 字符串到 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
---------------------------
【问题讨论】:
-
请不要在您的标题前加上“C#”之类的前缀。这就是标签的用途。
-
一些不是答案的注意事项:1) 你的流和 BinaryReader 应该在
using块中,以确保在你完成它们后及时处理它们,即使有例外抛出。 2) 不要使用Convert.ToString(_Exception.Message))。Message已经是一个字符串。此外,您最好使用_Exception.ToString(),它将显示完整的异常。