How to View the downloaded file When another downl

2019-08-17 11:08发布

I am implementing a mobile app using Xamarin android. I have implemented a code to download both.PDF and .Mobi file in a button click. I have used the below code.

  ...
        await Task.WhenAll(DownloadPDF(), DownloadMobi());
    }

    private async Task DownloadPDF()
    {
        var httpclient = new HttpClient(new AndroidClientHandler());
        using (var stream = await httpclient.GetStreamAsync("http://files/file.pdf"))
        using (var file = System.IO.File.Create("path/to/file.pdf"))
        {
            await stream.CopyToAsync(file);
            await file.FlushAsync();
        }
    }

    private async Task DownloadMobi()
    {
        var httpclient = new HttpClient(new AndroidClientHandler());

        using (var stream = await httpclient.GetStreamAsync("http://files/file.mobi"))
        using (var file = System.IO.File.Create("path/to/file.mobi"))
        {
            await stream.CopyToAsync(file);
            await file.FlushAsync();
    }
}

Its download both file at a same time. I want to download the PDF file at first. Once PDF file has been downloaded the button text should be changed to "View PDF" from "Download". When click View PDF the the file should be opened in PDF reader. The Mobile file download should start after this process and download should be in background. Can you anyone suggest your ideas to achieve this?

3条回答
贼婆χ
2楼-- · 2019-08-17 11:15

Since you're not showing any UI stuff i guess you have that covered to i will omit that.

Instead of writing: await Task.WhenAll(DownloadPDF(), DownloadMobi());

do the following

await DownloadPDF();
// update button to display "View PDF"
// add button click listener (optional if it's already registered)
// open file in PDF reader
await DownloadMobi();
查看更多
Animai°情兽
3楼-- · 2019-08-17 11:15

Use ContinueWith Method of Task

var task = DownloadPDF();
task.ContinueWith((pdfDownloadTask)=> DownloadMobi());

This will continue execution of next task after pdf download task is complete

查看更多
Animai°情兽
4楼-- · 2019-08-17 11:18
 private stringBuilder urlStr = null;
 public void DownloadFiles()
 {
   List<string> url = new List<string>();
   urlStr = new StringBuilder();
   url.add("http://files/file.pdf");
   url.add("http://files/file.mobi");
   var tasks = new List<Task>();
   foreach(var tempUrl in url)
   {
     tasks.add(DownloadMobiAndPdf(tempUrl);
   }
   Task.WhenAll(tasks));
 }

 private async Task DownloadMobiAndPdf(string url)
  {
    using(var client = new WebClient())
    {
       urlStr.Append(url);
       await client.DonwloadFileTaskAsync(url);
      client.DownloadFileCompleted+=Client_DownloadFileCompleted;
    }
  }




private static void Client_DownloadFileCompleted(object 
sender,System.ComponentModel.AsyncCompletedEventArgs e)
{

if(e.Error == null)
{
 //No error
 if(urlStr.Contains("pdf") 
 {
   //Enable button
 }

 }

 }
查看更多
登录 后发表回答