在Xamarin.Forms Web视图中打开本地HTML文件,不在资产文件夹中

时间:2019-03-14 13:23:41

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

我正在尝试打开一个多页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;

1 个答案:

答案 0 :(得分:0)

您需要确保以下几点:

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

2 http://myserver/test/test.htmlhttp://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")