【问题标题】:hex to bytes in chunks十六进制到块中的字节
【发布时间】:2012-06-03 17:23:26
【问题描述】:

我正在使用以下代码将写入 txt 文件的十六进制字符串转换为 字节文件。问题是它不能处理大的 txt 文件,我得到了 “内存不足异常”。我知道它应该以“块”的形式完成,但我不能 做对了。

请帮忙!代码:

protected void Button1_Click(object sender, EventArgs e)
{
    {
        string tempFileName = (Server.MapPath("~\\Tempfolder\\" + FileUpload2.FileName));

        using (FileStream fs = new FileStream(tempFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        using (StreamReader sr = new StreamReader(fs))
        {

            string s = (sr.ReadToEnd());
            if (s.Length % 2 == 1) { lblispis.Text = "String must have an even length"; }
            else
            {
               string hexString = s;
                File.WriteAllBytes(tempFileName + ".bin", StringToByteArray(hexString));
                lblispis.Text = "Done.";
            }
        }
    }                            
 }
public static byte[] StringToByteArray(String hex)
{
    int NumberChars = hex.Length;
    byte[] bytes = new byte[NumberChars / 2];
    for (int i = 0; i < NumberChars; i += 2)
        bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
    return bytes;
}

【问题讨论】:

    标签: c# hex bytebuffer


    【解决方案1】:

    如果文件格式允许,您可以将 ReadToEnd 调用替换为 ReadLine 并将其包装在一个循环中。

    如果不是这种情况,则始终可以选择读取偶数个字符 (Read(char[], int, int)),直到您到达文件末尾。当然,这样你在完成相当多的工作后很晚才检测到奇数个字符。

    【讨论】:

      【解决方案2】:

      要添加到@Wormbo 的答案,请注意十六进制字符串仅包含两倍于字节数组的字符。在 .NET 中,对象大小限制为 2GB(2GB 实际上是 32 位机器上的进程大小限制),但由于堆碎片,即使是 ~800MB 连续块也很容易分配问题。

      换句话说,您将希望在转换后立即直接写入磁盘:

      using (StreamReader reader = new StreamReader(hex))
      using (BinaryWriter writer = new BinaryWriter(File.Open(bin, FileMode.Create)))
      {
           string line;
           while ((line = reader.ReadLine()) != null)
               writer.Write(StringToByteArray(line));
      }
      

      [编辑]

      我已经修复它,必须在赋值周围添加括号(检查上面的 while 语句)。

      请注意,这只是以下内容的简写:

           string line = reader.ReadLine();
           while (line != null) 
           {
                writer.Write(...);
                line = reader.ReadLine();
           }
      

      【讨论】:

      • while (line = reader.ReadLine() != null) "不能将字符串类型隐式转换为布尔值"
      • 如果我这样做:string line = reader.ReadLine(); while (reader.ReadLine() != null) { writer.Write(StringToByteArray(line)); } 我得到空文件。
      • @Ladislav:对不起,我没有检查就写了。它基本上是一行中的两个操作:1)将一行读入line变量,2)检查line是否为空。但后一种操作具有优先权,因此编译器尝试将布尔值分配给line 变量。我会编辑。
      猜你喜欢
      • 2017-09-13
      • 2015-08-08
      • 2023-03-14
      • 2012-01-24
      • 2011-01-30
      • 1970-01-01
      • 1970-01-01
      • 2011-12-09
      相关资源
      最近更新 更多