【问题标题】:Open Local HTML files in Xamarin.Forms Web View NOT in Assets Folder在 Xamarin.Forms Web 视图中打开本地 HTML 文件而不是在资产文件夹中
【发布时间】:2019-03-14 13:23:40
【问题描述】:

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

我尝试使用的网址如下:

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;

【问题讨论】:

  • System.IO.Path.Combine("file://" + directory, "Test.html") 解析到什么?您是否为 html 文件设置了有效的文件 Url?
  • file:///data/user/0/com.test/files/HTML/Test.html
  • 经过一番谷歌搜索后,我发现 WebView 使用单独的 AppData 文件夹运行,无法访问主 AppData 文件夹。
  • 我已经发布了您的问题的答案,请尝试一下。

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


【解决方案1】:

您必须确保以下几点:

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 2018-02-19
    • 1970-01-01
    • 2010-12-28
    • 1970-01-01
    • 2014-08-25
    • 1970-01-01
    • 1970-01-01
    • 2013-12-06
    • 2018-12-31
    相关资源
    最近更新 更多