Windows商店获取下载进度
本文关键字:下载 获取 Windows | 更新日期: 2023-09-27 18:04:01
经过很长一段时间的挣扎,我终于得到了一个代码下载文件使用身份验证和发送一个头与范围在一个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));
如果从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);
}