I can download byte[]'s and write them to a file no problem, much link this link does. But when I make a simple alteration, saving the bytes[] and readCount to a List and then foreach over the list, I get a corrupt file.
Below is partial code that shows what I mean. There are two commented paths: one stores the bytes/counts (and order) and then writes when the reading is complete. The other writes in line with the each read.
Because of the order field, I have verified that the foreach is writing the bytes in the correct order but the partial code listing doesn't explicitly use it.
private class ByteHolder
{
public byte[] Buffer { get; set; } = new byte[8192];
public int BytesRead { get; set; }
public int Order { get; set; }
}
var byteList = new List<ByteHolder>();
using (var fileStream = new FileStream(_fileBytes.SavingPath.RuntimePath(), FileMode.Create, FileAccess.Write, FileShare.None, 8192, true))
{
do
{
var bytesRead = await contentStream.ReadAsync(buffer, 0, buffer.Length);
if (bytesRead == 0)
{
//--- WRITING THE bytes and counts this way produces corrupt file -->
var offset = 0;
foreach (var byteHolder in byteList)
{
await fileStream.WriteAsync(byteHolder.Buffer, offset, byteHolder.BytesRead).ConfigureAwait(false);
offset += 8192;
}
isMoreToRead = false;
FileDownloadComplete?.Invoke(this, _fileBytes);
continue;
}
//--- Storing them in this class and list for writing above DOES NOT WORK -->
byteList.Add(new ByteHolder() { Buffer = buffer, BytesRead = bytesRead, Order = readCount });
//--- Writing inline with the read WORKS -->
//await fileStream.WriteAsync(buffer, 0, bytesRead);
readCount++;
totalBytesRead += bytesRead;