I'm trying to implement the download of a given url. By the way my code is:
private string url; private StorageFile outputFile; public void download() { HttpWebRequest request = HttpWebRequest.CreateHttp(url); request.BeginGetResponse(new AsyncCallback(playResponseAsync), request); } public async void playResponseAsync(IAsyncResult asyncResult) { //Declaration of variables HttpWebRequest webRequest = (HttpWebRequest)asyncResult.AsyncState; try { using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncResult)) { byte[] buffer = new byte[1024]; using (var writeStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite)) { using (var outputStream = writeStream.GetOutputStreamAt(0)) { using (var dataWriter = new DataWriter(outputStream)) { using (Stream input = webResponse.GetResponseStream()) { var totalSize = 0; for (int size = input.Read(buffer, 0, buffer.Length); size > 0; size = input.Read(buffer, 0, buffer.Length)) { dataWriter.WriteBytes(buffer); totalSize += size; //get the progress of download } await dataWriter.StoreAsync(); await outputStream.FlushAsync(); dataWriter.DetachStream(); } } } } Debug.WriteLine("Finished"); } } catch { } } } I'd like my download method to have the following signature
Task<bool> download(); (Returning true if the download succeeded and false otherwise)
making it an awaitable task. But I do not master C# and don't know how to do it. Can you help me?
Thanks