【问题标题】:How to speed up writing large byte array to afile?如何加快将大字节数组写入文件的速度?
【发布时间】:2013-01-14 12:23:24
【问题描述】:

我需要将十六进制字符串转换为字节数组,然后将其写入文件。下面的代码给出了 3 秒 的延迟。 hex下面是一个长度为1600的十六进制字符串。有没有其他方法可以加快速度?

        Stopwatch sw = new Stopwatch();
        sw.Start();
        for (int i = 0; i < 5000; i++)
        {

            FileStream objFileStream = new FileStream("E://CRec Correcting Copy//Reader//bin//Debug//Files//Raw Data//a123.txt", FileMode.Append, FileAccess.Write);
            objFileStream.Seek(0, SeekOrigin.End);
            objFileStream.Write(stringTobyte(hex), 0, stringTobyte(hex).Length);
            objFileStream.Close();
        }
        sw.Stop();
        Console.WriteLine(sw.ElapsedMilliseconds);

stringTobyte 是一种将十六进制字符串转换为字节数组的方法。

public static byte[] stringTobyte(string hexString)
    {
        try
        {
            int bytesCount = (hexString.Length) / 2;
            byte[] bytes = new byte[bytesCount];
            for (int x = 0; x < bytesCount; ++x)
            {
                bytes[x] = Convert.ToByte(hexString.Substring(x * 2, 2), 16);
            }
            return bytes;
        }
        catch
        {
            throw;
        }
    }

请告诉我延迟发生在哪里?

【问题讨论】:

  • 为什么要创建/打开/搜索/写入/关闭 5,000 次?什么可能会让某人认为这是明智的?这就像开车去商店 50 次才能得到 50 个苹果!随心所欲地打开、搜索、写入,然后关闭。
  • 只打开一次流,写入几KB的块而不是一个字节。
  • 请告诉我,这段代码是故意创建的,作为糟糕代码的示例或“优化这段代码”练习。
  • 十六进制总是空的吗? 5000 循环可能与时间有关……您几乎可以立即将 1600 字节的数据放入文件中。所以你的代码肯定有问题。最有可能与循环有关。
  • 为什么需要stringTobyte,什么时候System.Encoding.Ascii.getbytes()会做你想做的事

标签: c# hex byte filestream


【解决方案1】:

你想方式复杂。首先,不需要您的自定义函数将其转换为字节数组。 System.Text.UTF8Encoding.GetBytes(string) 会为您做到这一点!另外,这里不需要流,看看File.WriteAllBytes(string, byte[]) 方法。

那么它应该是这样的:

System.IO.File.WriteAllBytes("E://CRec Correcting Copy//Reader//bin//Debug//Files//Raw Data//a123.txt", new System.Text.UTF8Encoding().GetBytes(hex));

或多行版本,如果您坚持:

string filePath = "E://CRec Correcting Copy//Reader//bin//Debug//Files//Raw Data//a123.txt";
System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
byte[] bytes = encoder.GetBytes(hex);
System.IO.File.WriteAllBytes(filePath, bytes);

【讨论】:

  • voice = Encoding.ASCII.GetBytes(objCallFields.Payload); objFileStream = new FileStream(rawdataPath + objCallFields.callID + ".raw", FileMode.Append, FileAccess.Write); objFileStream.Seek(0, SeekOrigin.End); objFileStream.Write(voice, 0, voice.Length); objFileStream.Close(); objCallFields.Payload = BitConverter.ToString(list.ToArray()).Replace("-", "");
【解决方案2】:

哇。首先这样做:

objFileStream.Write(stringTobyte(hex), 0, stringTobyte(hex).Length);


byte[] bytes = stringTobyte(hex);
objFileStream.Write(bytes , 0, bytes.Length);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-25
    • 2015-04-19
    • 2017-07-29
    • 2020-02-06
    • 1970-01-01
    • 2015-01-27
    • 2019-11-24
    相关资源
    最近更新 更多