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

Windows Phone: How to load html in webview from a local file

我有一个 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\Packagesf4082ad-ad69-4cb8-8749-751ee4c5e46d_x2xndhe6jjw20\LocalState\mobile.html

可以使用WebView的NavigateToLocalStreamUri方法

例如

在 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 解析器 class

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");
            }
        }
    }