将下载的zip文件保存到本地文件

时间:2015-08-06 15:04:15

标签: c# android .net xamarin stream

我试图保存我从服务器下载的zip文件流。 现在我Stream但我无法保存到文件中。这是我的尝试=>

 private async Task DownloadCompleted(Stream inputStream, CancellationToken ct)
    {
        var file = await _downloadFolder.CreateFileAsync(_productDescription.ProductFileName, CreationCollisionOption.ReplaceExisting, ct);
        using (Stream str = await file.OpenAsync(FileAccess.ReadAndWrite, ct))
        {
            await inputStream.CopyToAsync(str);
        }
     }

我试图这样做Xamarin.Android项目,我不擅长溪流,也非常赞赏一些好的指针。

编辑 - 这里我得到了流

  private async Task DownloadFileFromUrl(string url, CancellationToken ct)
    {
        try
        {
            var receivedBytes = 0;
            using (var client = new WebClient())
            using (var stream = await client.OpenReadTaskAsync(url))
            {
                var buffer = new byte[4096];
                var totalBytes = int.Parse(client.ResponseHeaders[HttpResponseHeader.ContentLength]);

                for (;;)
                {
                    var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, ct);
                    if (bytesRead == 0)
                    {
                        await Task.Yield();
                        break;
                    }
                    receivedBytes += bytesRead;
                    if (_downloadProgressHandler != null)
                    {
                        _downloadProgressHandler((int)(((double)receivedBytes / totalBytes) * 100), false);
                    }
                }
                await DownloadCompleted(stream, ct);
            }
        }
        catch (System.OperationCanceledException)
        {
            throw;
        }
        catch (Exception ex)
        {
            Analytics.AddHandledExceptionEvent(ex, "Ex-ProductDownloader-DownloadFileFromUrl");
            throw new NetworkNotAvailableException("");
        }
    }

0 个答案:

没有答案