Windows商店获得下载进度

时间:2014-05-17 11:43:38

标签: c# download windows-store-apps windows-8.1

经过长时间的努力,我终于得到了一个代码,用于使用身份验证下载文件并在Windows应用商店应用程序中发送带有范围的标题,现在下一级是获取下载的进度条,所以任何应该用于获取下载操作的类和方法的想法?

这是我的代码:

var httpClientHandler = new HttpClientHandler();
httpClientHandler.Credentials = new System.Net.NetworkCredential("", "");
var client = new HttpClient(httpClientHandler);

System.Net.Http.HttpRequestMessage request = new System.Net.Http.HttpRequestMessage(HttpMethod.Post, new Uri(""));
request.Headers.Range = new RangeHeaderValue(0,null);
HttpResponseMessage response = await client.SendAsync(request);              
Stream stream = await response.Content.ReadAsStreamAsync();
StorageFile file = await folder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName);
await Windows.Storage.FileIO.WriteBytesAsync(file, ReadStream(stream));

1 个答案:

答案 0 :(得分:2)

如果您从System.Net.Http.HttpClient切换到Windows.Web.Http.HttpClient,则此任务会更容易。

using Windows.Web.Http;
using Windows.Web.Http.Filters;

private async void Foo(StorageFolder folder, string fileName)
{

    Uri uri = new Uri("http://localhost");
    var filter = new HttpBaseProtocolFilter();
    filter.ServerCredential =
        new Windows.Security.Credentials.PasswordCredential(uri.ToString(), "foo", "bar");
    var client = new HttpClient(filter);

    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uri);
    request.Headers.Add("Range", "bytes=0-");

    // Hook up progress handler.
    Progress<HttpProgress> progressCallback = new Progress<HttpProgress>(OnSendRequestProgress);
    var tokenSource = new CancellationTokenSource();
    HttpResponseMessage response = await client.SendRequestAsync(request).AsTask(tokenSource.Token, progressCallback);

    IInputStream inputStream = await response.Content.ReadAsInputStreamAsync();
    StorageFile file = await folder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName);

    // Copy from stream to stream.
    IOutputStream outputStream = await file.OpenAsync(FileAccessMode.ReadWrite);
    await RandomAccessStream.CopyAndCloseAsync(inputStream, outputStream);
}

private void OnSendRequestProgress(HttpProgress obj)
{
    Debug.WriteLine(obj);
}

否则,请查看at this other answer