Windows phone 8.1 Windows Phone:如何从本地文件在webview中加载html
我有一个html字符串,它有本地css和js路径。但是Html不能处理这些本地路径。我们仔细研究过,但在每一个例子中,他们都加载了带有内联编写的html。但是我必须工作,而且有太多的css,js断言。如果我写内联,我担心它会加载缓慢,我认为这是毫无意义的。然后我决定更改一个本地html文件并从该文件加载html 如何从本地文件加载html 这是我的示例代码:Windows phone 8.1 Windows Phone:如何从本地文件在webview中加载html,windows-phone-8.1,Windows Phone 8.1,我有一个html字符串,它有本地css和js路径。但是Html不能处理这些本地路径。我们仔细研究过,但在每一个例子中,他们都加载了带有内联编写的html。但是我必须工作,而且有太多的css,js断言。如果我写内联,我担心它会加载缓慢,我认为这是毫无意义的。然后我决定更改一个本地html文件并从该文件加载html 如何从本地文件加载html 这是我的示例代码: StorageFolder localFolder = Windows.Storage.ApplicationDat
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\u x2xndhe6jw20\LocalState\mobile.html
您可以使用WebView的NavigateLocalStreamUri方法
e、 g
在WebView中加载事件
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");
}
}
}
公共密封类LocalUriResolver:IUriToStreamResolver
{
公共IAsyncOperation UriToStreamAsync(Uri)
{
if(uri==null)
{
抛出新异常();
}
字符串路径=uri.AbsolutePath;
返回GetContent(path).asAsAsAsyncOperation();
}
专用异步任务GetContent(字符串路径)
{
尝试
{
Uri localUri=新Uri(“ms-appdata:///local“+uriPath);
StorageFile文件=等待StorageFile.GetFileFromApplicationUriAsync(localUri);
irandomaccesstream=await file.OpenReadAsync();
返回流GetInputStreamAt(0);
}
捕获(例外)
{
抛出新异常(“无效路径”);
}
}
}
将html文件读入字符串并使用NavigateToString。