首页 > 解决方案 > 在 Xamarin.Forms Web 视图中打开本地 HTML 文件而不是在资产文件夹中

问题描述

我正在尝试打开一个多页 HTML 网页(即 test.html、test.css 和 test.js),该网页已动态下载(因此无法使用资产)并存储在应用程序内部存储中(Xamarin.Essentials.FileSystem .AppDataDirectory)。

我尝试使用的 URL 如下:

file:///data/user/0/com.test/files/HTML/Test.html

但是我只是找不到文件。

        var filesToDownload = new string[] { "http://myserver/test/test.html", "http://myserver/test/test.css" };
        var directory = System.IO.Path.Combine(Xamarin.Essentials.FileSystem.AppDataDirectory, "HTML");

        if (System.IO.Directory.Exists(directory))
        {
            System.IO.Directory.Delete(directory, true);
        }

        System.IO.Directory.CreateDirectory(directory); 

        using (var wc = new System.Net.WebClient())
        {
            foreach (var f in filesToDownload)
            {
                wc.DownloadFile(f, System.IO.Path.Combine(directory, System.IO.Path.GetFileName(f)));
            }
        }

        var source = new UrlWebViewSource
        {
            Url = System.IO.Path.Combine("file://" + directory, "Test.html")
        };

        WebView1.Source = source;

标签: c#xamarin.formsxamarin.forms.webview

解决方案


您必须确保以下几点:

1 将Xamarin.Essentials NuGet包添加到每个项目

2http://myserver/test/test.html并且http://myserver/test/test.css存在且可访问。

3 webview源的文件名应该和你写入存储的文件名一致。不是Test.html,而是test.html

所以 Url = System.IO.Path.Combine("file://" + directory, "Test.html")应该修改为

Url = System.IO.Path.Combine("file://" + directory, "test.html")


推荐阅读