Search code examples
c#windows-runtimewindows-store-apps

Append IBuffer to byte[]


I have this method to download a file on a windows 8 project

try{
byte[] data;
...

    Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient();

                    client.DefaultRequestHeaders.TryAppendWithoutValidation(
                        "Authorization",
                         "Bearer " + App.Current.Resources["token"] as string);

                    Uri uri = new Uri(Constants.baseAddress + "meeting/points/attachments/download?meetingId=" + meetingId + "&pointId=" + pointId + "&attachmentId=" + attachmentId);


                        Windows.Web.Http.HttpResponseMessage response = await client.GetAsync(uri, Windows.Web.Http.HttpCompletionOption.ResponseHeadersRead);

                        IInputStream inputStream = await response.Content.ReadAsInputStreamAsync();

                        ulong totalBytesRead = 0;
                        while (true)
                        {
                            // Read from the web.
                            IBuffer buffer = new Windows.Storage.Streams.Buffer(1024);

                            buffer = await inputStream.ReadAsync(
                                buffer,
                                buffer.Capacity,
                                InputStreamOptions.None);

                            if (buffer.Length == 0)
                            {
                                // There is nothing else to read.
                                break;
                            }

                            // Report progress.
                            totalBytesRead += buffer.Length;
                            System.Diagnostics.Debug.WriteLine("Bytes read: {0}", totalBytesRead);

                            // Write to file.
                        }

                        inputStream.Dispose();

                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }

I would like to append the bytes i get in the buffer to the data variable, so that in the end i have all bytes saved in the data

How can i do that?


Solution

  • The code for reading all bytes for writing it to a file:

    byte[] data;
    IInputStream inputStream = await response.Content.ReadAsInputStreamAsync();
    data = new byte[inputStream .Length];
    inputStream.Read(data, 0, (int)inputStream.Length);
    
    //Save the file here (data)