WP8 - WebBrowser类:如何处理文件下载?

时间:2013-03-10 08:03:57

标签: windows-phone-8 download webbrowser-control

我在WP8中创建了一个简单的应用程序,使用Microsoft.Phone.Controls.WebBrowser类显示网页。 我能够加载页面,导航链接,在历史记录中前后移动。 除了这个基本功能外,我还想提供一些方法来下载无法在浏览器中显示的文件,比如说.ppt或.mp3。

我无法在WebBrowser类文档中找到任何内容来启动下载。只有一个Navigate函数可以加载URL。

那么可以使用WebBrowser类完成下载吗?

1 个答案:

答案 0 :(得分:1)

您必须拦截导航事件并自行处理。

以下代码示例应指向正确的方向。 (你需要对它进行改进,我只是把它放在一起表明它可以与我在搜索测试mp3文件时出现在Google上的随机mp3网站一起工作)

using Microsoft.Phone.Controls;
using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Net;
using System.Threading.Tasks;
using System.Windows;

namespace PhoneApp2
{
    public partial class MainPage
    {
        public MainPage()
        {
            InitializeComponent();
            MyWebBrowser.Navigate(new Uri("http://robtowns.com/music/"));
        }

        private async void MyWebBrowser_OnNavigating(object sender, NavigatingEventArgs e)
        {
            if (!e.Uri.AbsolutePath.EndsWith(".mp3")) return; //Find a more reliable way to detect mp3 files

            e.Cancel = true; // Cancel the browser control navigation, and take over from here

            MessageBox.Show("Now downloading an mp3 file");
            var fileWebStream = await GetStream(e.Uri);

            using(var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                var filePath = "downloadedfile.mp3";
                var localFile = isolatedStorage.CreateFile(filePath);
                await fileWebStream.CopyToAsync(localFile.AsOutputStream().AsStreamForWrite());
                fileWebStream.Close();
                MessageBox.Show("File saved as 'downloadedfile.mp3'");
            }
        }

        public static Task<Stream> GetStream(Uri url)
        {
            var tcs = new TaskCompletionSource<Stream>();
            var wc = new WebClient();
            wc.OpenReadCompleted += (s, e) =>
            {
                if (e.Error != null) tcs.TrySetException(e.Error);
                else if (e.Cancelled) tcs.TrySetCanceled();
                else tcs.TrySetResult(e.Result);
            };
            wc.OpenReadAsync(url);
            return tcs.Task;
        }
    }
}