我有一种方法可以将文件转换为字节,以便稍后可以通过互联网发送它。无论如何,因为我计划发送大文件,所以我发送大块文件而不是发送整个文件。每个块由一个字节数组 (byte[]) 组成。我对这一切都很陌生,所以我想在发送之前将每个块保存在块列表(List)中。所以我的课程看起来像:
public class SomeClass
{
public List<byte[]> binaryFileList;
public void SendChunk(byte[] data, int index)
{
binaryFileList.Add(data);
// later I will add code in here to do something with data
}
public void test(string path)
{
binaryFileList = new List<byte[]>();
System.IO.FileStream stream = new System.IO.FileStream(path,
System.IO.FileMode.Open, System.IO.FileAccess.Read);
var MaxChunkSize = 10000;
byte[] chunk = new byte[MaxChunkSize];
while (true)
{
int index = 0;
// There are various different ways of structuring this bit of code.
// Fundamentally we're trying to keep reading in to our chunk until
// either we reach the end of the stream, or we've read everything we need.
while (index < chunk.Length)
{
int bytesRead = stream.Read(chunk, index, chunk.Length - index);
if (bytesRead == 0)
{
break;
}
index += bytesRead;
}
if (index != 0) // Our previous chunk may have been the last one
{
SendChunk(chunk, index); // index is the number of bytes in the chunk
}
if (index != chunk.Length) // We didn't read a full chunk: we're done
{
return;
}
}
}
}
当我执行时:
SomeClass s = new SomeClass();
s.test(@"A:\Users\Tono\Desktop\t.iso");
binaryFileList 列表填充文件块:A:\Users\Tono\Desktop\t.iso
现在,当我从该数据创建文件时,问题就出现了。调试时,我注意到问题是因为二进制 FileList 中的项目在我输入数据时发生了变化。让我告诉你我的意思:
请注意,在此调试中,这是我第一次向 binaryFileList 添加项目。而且您还可以看到数组中该项目的每个字节......
现在我将让该方法运行更多次,向二进制 FileList 添加更多项目。
所以现在 binaryFileList 有 278 个项目,而不是最后一张图片中的项目:
所以到目前为止一切看起来都还不错吧?但是你们还记得二进制文件列表的第一项包含一个几乎全是 0 的字节数组吗?看一下二进制 FileList 的第一项:
当我不断向二进制 FileList 添加项目时,请注意第一个项目如何变化:
换句话说,binaryFileList 是一个 byte[] 列表。当我向 binaryFileList 添加一个 byte[] 时,其他 byte[] 不应改变。他们确实改变了!为什么!?