拆分数据并将其放回原处 [英] Split data and put it back together

查看:57
本文介绍了拆分数据并将其放回原处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实际上,这比实践更重要。对于这个问题,我感到最沮丧的是,这对我来说是一个相当新的概念。我将在下面发布我的代码。

This is more for practice than anything, really. I am having the most frustrating time with this as it's a fairly new concept to me. I will post my code below.

我要尝试执行的操作:


  1. 将文件读入字节数组

  2. 将字节拆分为预定义大小的pars

  3. 将各部分放回原处,然后编写将文件保存为高清

  1. Read a file into a byte array
  2. Split the byte into pars of a predefined size
  3. Put the parts back together, and write the file to HD

byte [] sData = File.ReadAllBytes(@ C:\Project1.exe); // 16,384字节

byte[] sData = File.ReadAllBytes(@"C:\Project1.exe"); // 16,384 bytes

// Split the data up here
                int range = 8;
                range *= 1024;
                int pos = 0;
                int remaining;
                int i = 0;
                byte[] test = null;
                while ((remaining = sData.Length - pos) > 0)
                {
                    byte[] block = new byte[Math.Min(remaining, range)];
                    test = new byte[block.Length + pos];
                    Array.Copy(sData, pos, test, pos, block.Length);
                    pos += block.Length;
                    i++;
                }

                File.WriteAllBytes(@"C:\blank.exe", test);


文件 blank.exe始终是

The file "blank.exe" is always corrupt.

有人在这里看到我的错误了吗?

Does anyone see my error(s) here?

我很感激,埃文

推荐答案

您正在重新创建测试遍历循环的数组。

You are recreating the test array on each pass through the loop.

这意味着当您将测试数组末尾写入文件时,您只写了处理的最后一块数据。

This means when you write the test array to the file at the end, you are only writing the last block of data that you processed.

您有几个选择:

1)在每次通过时调整数组的大小,然后将先前的数据复制到新数组中。这将是非常低效的。

1) Resize the array on each pass and copy the previous data into the new array. This would be very inefficient. This is the same mechanism that Array.Resize uses.

2)如果您提前知道所需的数组大小(即与数据大小相同),则使用Array.Resize。您可以从文件中读取文件或文件大小的倍数),然后只需在进入循环之前调整数组的大小即可。

2) If you know the desired size of the array ahead of time (i.e. it is the same size as the data you read from the file or a multiple of the file size), then just resize the array one time before entering the loop.

3)使用其他数据结构,例如作为List或ArrayList。

3) Use a different data structure, such as as List or an ArrayList.

这篇关于拆分数据并将其放回原处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆