将文件逐行复制到另一个文件的正确方法?

问题描述 投票:0回答:1

我需要打开一个文件,读一行,如果该行尊重某些条件将其写入另一个文件,我正在阅读的行是一个普通的ASCII字符串代表HEX值,我需要将其粘贴到一个新文件中作为HEX值而不是ASCII字符串。

我有的是这个:

private void Button_Click(object sender, RoutedEventArgs e)
{
    byte[] arrayByte = { 0x00 };
    var linesToKeep = File.ReadLines(fileName).Where(l => l.Contains(":10"));
    foreach (string line in linesToKeep)
    {

        string partialA = line.Substring(9);
        string partialB = partialA.Remove(partialA.Length - 2);
        arrayByte = ToByteArray(partialB);
        using (var stream = new FileStream(fileName+"_gugggu", FileMode.OpenOrCreate))
        {
            FileInfo file = null;
            file = new FileInfo(fileName + "_gugggu");
            stream.Position = file.Length;
            stream.Write(arrayByte, 0, arrayByte.Length);
        }
    }
}
public static byte[] ToByteArray(String HexString)
{
    int NumberChars = HexString.Length;
    byte[] bytes = new byte[NumberChars / 2];
    for (int i = 0; i < NumberChars; i += 2)
    {
        bytes[i / 2] = Convert.ToByte(HexString.Substring(i, 2), 16);
    }
    return bytes;
}

这种方法正在做我需要的但是需要很长时间才能完成,原始文件大约有70000行...有没有更好的方法来提高速度?

c# filestream streamwriter
1个回答
0
投票

如评论中所述,您几乎可以继续打开和关闭目标文件。您对源文件中的每一行执行此操作,这会导致巨大且不必要的开销。

每次从源文件中读取一行时,都无需关闭,重新打开和重新设置流位置。

我创建了一个316240行的文件。下面的代码读取,确定要保留哪些行,然后将它们写入目标文件。由于我无法访问您的源文件,因此我使用了某种字符串到字节的转换模型。

结果:

Test_Result

如你所见,它在1/3秒内完成。

码:

private Stopwatch sw = new Stopwatch();
private FileInfo _sourceFile = new FileInfo(@"D:\source.txt");
private FileInfo _destinationFile = new FileInfo(@"D:\destination.hex");

private void ConvertFile()
{
    sw.Start();
    using (var streamReader = new StreamReader(_sourceFile.OpenRead()))
    {
        using (var streamWrite = _destinationFile.OpenWrite())
        {
            while (!streamReader.EndOfStream)
            {
                string line = streamReader.ReadLine();
                if (line.Contains(" x"))
                {
                    var array = ToByteArray(line);
                    streamWrite.Write(array, 0, array.Length);
                }
            }
        }
    }
    sw.Stop();
    MessageBox.Show("Done in " + sw.Elapsed);
}

private byte[] ToByteArray(string hexString)
{
    return hexString.ToList().ConvertAll(c => Convert.ToByte(c)).ToArray();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    ConvertFile();
}

HTH

© www.soinside.com 2019 - 2024. All rights reserved.