【问题标题】:How can I open a .pdf file in the browser from a Xamarin UWP project?如何在浏览器中从 Xamarin UWP 项目打开 .pdf 文件?
【发布时间】:2019-08-26 17:03:21
【问题描述】:

我有一个 Xamarin 项目,我从头开始生成一个 .pdf 文件并将其保存在我的本地存储中。这工作得很好,可以找到它并在我保存它的磁盘中打开它。但是,我需要在以编程方式创建后立即打开 .pdf 文件。

我已经使用 Process 和 ProcessStartInfo 尝试了不同的变体,但这些只会引发错误,例如“System.ComponentModel.Win32Exception:'系统找不到指定的文件'”和“'System.PlatformNotSupportedException'”。

这基本上是我尝试使用 Process 打开的路径。


var p = Process.Start(@"cmd.exe", "/c start " + @"P:\\Receiving inspection\\Inspection Reports\\" + timestamp + ".pdf");


我还尝试了使用一些变体的 ProcessStartInfo,但我一遍又一遍地遇到相同的错误。

var p = new Process();
p.StartInfo = new ProcessStartInfo(@"'P:\\Receiving inspection\\Inspection Reports\\'" + timestamp + ".pdf");
p.Start();

【问题讨论】:

  • 如何使用基于file:///的uri打开浏览器:docs.microsoft.com/en-us/xamarin/essentials/…
  • 感谢您的回答。我尝试了您的建议,但没有任何反应。我不知道我构建 Uri 的方式是否有问题或其他问题。这是Uri:Uri uri = new Uri("file:///P:/Receiving Inspection/Inspection Reports/" + timestamp + ".pdf");我正在调用的方法: public async Task OpenBrowser(Uri uri) { await Browser.OpenAsync(uri, BrowserLaunchMode.SystemPreferred); }
  • file:/// 协议在 uwp 中不起作用。
  • 更好的方法是使用LaunchFileAsync方法用浏览器打开文件。
  • @NoelRT 这不是格式正确的基于文件的 uri

标签: c# xamarin uwp


【解决方案1】:

更好的方法是使用LaunchFileAsync 方法用浏览器打开文件。您可以创建 FileLauncher DependencyService 以从 xamarin 共享项目中调用 uwp LaunchFileAsync 方法。

界面

public interface IFileLauncher
{
    Task<bool> LaunchFileAsync(string uri);
}

实施

[assembly: Dependency(typeof(UWPFileLauncher))]

namespace App14.UWP
{
    public class UWPFileLauncher : IFileLauncher
    {
        public async Task<bool> LaunchFileAsync(string uri)
        {
            var file = await Windows.Storage.StorageFile.GetFileFromPathAsync(uri);
            bool success = false;
            if (file != null)
            {
                // Set the option to show the picker
                var options = new Windows.System.LauncherOptions();
                options.DisplayApplicationPicker = true;

                // Launch the retrieved file
                 success = await Windows.System.Launcher.LaunchFileAsync(file, options);
                if (success)
                {
                    // File launched
                }
                else
                {
                    // File launch failed
                }
            }
            else
            {
                // Could not  
            }
            return success;
        }
    }
}

用法

private async void Button_Clicked(object sender, EventArgs e)
{        
  await DependencyService.Get<IFileLauncher>().LaunchFileAsync("D:\\Key.pdf");
}

请注意,如果你想在 uwp 中访问 D 或 C 盘,你需要添加broadFileSystemAccess 能力。更多信息请参考this

更新

如果 UWP 文件是基于网络的,而不是基于本地区域的,您可以使用 Xamarin.Essentials 使用浏览器打开文件。并且您必须在清单中指定 privateNetworkClientServer 功能。更多信息请参考link

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-02
    • 2019-01-04
    • 2017-01-20
    相关资源
    最近更新 更多