Windows Phone:如何从本地文件加载webview中的html

时间:2015-04-27 10:28:19

标签: windows-phone-8.1

我有一个html字符串,它有本地css,js路径。但是Html没有使用这些本地路径。我们搜索但是在每个例子中,他们都加载了带内联写入的html。但我必须工作断开连接,有很多css,js断言。如果我写内联,我担心它会加载缓慢,我认为它是如此毫无意义。然后我决定更改本地html文件并从该文件加载html。

如何从本地文件加载html?

这是我的示例代码:

   StorageFolder localFolder =
        Windows.Storage.ApplicationData.Current.LocalFolder;


           string desiredName = "mobile.html";
           StorageFile newFile =
               await localFolder.CreateFileAsync(desiredName,CreationCollisionOption.OpenIfExists);

           using (var stream = await newFile.OpenStreamForWriteAsync())
                  {
                      stream.Write(fileBytes, 0, fileBytes.Length);
                  }

             webViewFormResponse.Source = new Uri(newFile.Path);

newFile.Path喜欢这样:C:\Data\Users\DefApps\APPDATA\Local\Packages\9f4082ad-ad69-4cb8-8749-751ee4c5e46d_x2xndhe6jjw20\LocalState\mobile.html

1 个答案:

答案 0 :(得分:0)

您可以使用WebView的NavigateToLocalStreamUri方法

e.g。

在WebView Loaded事件中

private void WebView_Loaded(object sender, RoutedEventArgs e)
{    
    Uri uri = MyWebView.BuildLocalStreamUri("LocalData", "mobile.html");
    LocalUriResolver resolver = new LocalUriResolver();
    MyWebView.NavigateToLocalStreamUri(uri, resolver);
}

和Uri解析器类

public sealed class LocalUriResolver : IUriToStreamResolver
    {
        public IAsyncOperation<IInputStream> UriToStreamAsync(Uri uri)
        {
            if (uri == null)
            {
                throw new Exception();
            }
            string path = uri.AbsolutePath;
            return GetContent(path).AsAsyncOperation();
        }

        private async Task<IInputStream> GetContent(string uriPath)
        {
            try
            {
                Uri localUri = new Uri("ms-appdata:///local" + uriPath);
                StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(localUri);
                IRandomAccessStream stream = await file.OpenReadAsync();
                return stream.GetInputStreamAt(0);
            }
            catch (Exception)
            {
                throw new Exception("Invalid path");
            }
        }
    }