您的位置:首页 > 移动开发

UWP保存网页到本地

2016-05-25 09:46 288 查看
布局文件

<Page

    x:Class="webrequestWeb.MainPage"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:local="using:webrequestWeb"

    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

    mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

        <StackPanel>

            <WebView Name="web" Height="340"/>

            <Button Name="btn" Height="40" Width="360"

                    Margin="10" Click="btn_Click"

                    HorizontalAlignment="Center"

                    />

        </StackPanel>

    </Grid>

</Page>

代码

using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Net;

using System.Runtime.InteropServices.WindowsRuntime;

using Windows.Foundation;

using Windows.Foundation.Collections;

using Windows.Storage;

using Windows.UI.Xaml;

using Windows.UI.Xaml.Controls;

using Windows.UI.Xaml.Controls.Primitives;

using Windows.UI.Xaml.Data;

using Windows.UI.Xaml.Input;

using Windows.UI.Xaml.Media;

using Windows.UI.Xaml.Navigation;

//“空白页”项模板在 http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 上有介绍

namespace webrequestWeb

{

    /// <summary>

    /// 可用于自身或导航至 Frame 内部的空白页。

    /// </summary>

    public sealed partial class MainPage : Page

    {

        public MainPage()

        {

            this.InitializeComponent();

        }

        private async void btn_Click(object sender, RoutedEventArgs e)

        {

            var local = ApplicationData.Current.LocalFolder;

            var localStorageFolder = await local.CreateFolderAsync("File", CreationCollisionOption.OpenIfExists);

            var file = await localStorageFolder.CreateFileAsync("web.html",CreationCollisionOption.ReplaceExisting);

            var url = "http://www.baidu.com";

            List<Byte> allbytes = new List<byte>();

            using (var response = await WebRequest.Create(url).GetResponseAsync())

            {

                using (Stream responseStream = response.GetResponseStream())

                {

                    byte[] buffer = new byte[4000];

                    int bytesRead = 0;

                    while ((bytesRead = await responseStream.ReadAsync(buffer, 0, 4000)) > 0)

                    {

                        allbytes.AddRange(buffer.Take(bytesRead));

                    }

                }

            }

            await FileIO.WriteBytesAsync(file, allbytes.ToArray());

//测试是否保存好,直接用webview显示出来

            var webStringTemp = await FileIO.ReadTextAsync(file);

            var webString = webStringTemp.ToString();

            web.NavigateToString(webString);

        }

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C# uwp webview