2017-08-03 94 views
0

目前我正在開發UWP應用程序,因爲我需要將pdf和word url下載到系統下載文件夾中,因此需要我嘗試使用backgrounddownloader類,如下面的代碼所示。下載UWP中的PDF和Word文件

Uri source = new Uri(selectedfile.DocumentPath); 

      StorageFile destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
       selectedfile.DocumentName, CreationCollisionOption.GenerateUniqueName); 

      BackgroundDownloader downloader = new BackgroundDownloader(); 
      DownloadOperation download = downloader.CreateDownload(source, destinationFile); 

的還我試圖另闢蹊徑,在此下載網址是代碼

var request = WebRequest.CreateHttp(selectedfile.DocumentPath); 

      var sampleFile = await KnownFolders.PicturesLibrary.CreateFileAsync(selectedfile.DocumentName, CreationCollisionOption.GenerateUniqueName); 
       var cli = new HttpClient(); 
       var str = await cli.GetStreamAsync(request.RequestUri); 
       var dst = await sampleFile.OpenStreamForWriteAsync(); 
       await str.AsInputStream().AsStreamForRead().CopyToAsync(dst); 

對於使用上述兩種方法的URL可以下載PDF格式和文字,但我試圖打開pdf文件和word文件,但無法打開,顯示錯誤,如下圖trying to open the open downloaded file it shown like this所示。任何人都可以幫助解決這個問題。我想下載該文件,並且下載的文件應該是打開的。

+0

您尚未發佈完整的代碼。使用第一種方法,你是否等待下載完成?在第二個,你關閉目標流? –

+0

感謝您的回覆,在第一種方法中,我不會等待下載,它會自動下載並顯示圖片文件夾中的文件,我不知道上述方法是否正確,我只是在嘗試這種方法。 – Murali

+0

它應該是主機不給你預期的文件,也許是一個html文件。用記事本打開下載的文件,你會發現,如果是這樣的話。 –

回答

0

BackgroundDownloader.CreateDownload方法初始化一個DownloadOperation對象,該對象包含指定的Uri和寫入響應的文件。

當創建了DownloadOperation時,它不會開始下載操作。 我們應該可以使用DownloadOperation.StartAsync開始下載操作。

例如:

Uri source = new Uri(selectedfile.DocumentPath); 
StorageFile destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync("ab.pdf", CreationCollisionOption.GenerateUniqueName); 
BackgroundDownloader downloader = new BackgroundDownloader(); 
DownloadOperation download = downloader.CreateDownload(source, destinationFile); 
await download.StartAsync(); 

如果您想了解降負荷文件的更多細節,請參考Background transfer sample