user2469133 user2469133 - 2 months ago 21
C# Question

Windows store get download progress

After struggling for a long time i finally got a code for downloading a file with using authentication and sending a header with a range in a windows store application , now the next level is to get a progress bar of the download , so any idea of the classes and methods that should be used for getting the download operation?

This is my code:

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));

Answer

This task will be easier if you switch from System.Net.Http.HttpClient to 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);
}

Otherwise, take a look at this other answer.

Comments