Xamarin.Forms将文件(pdf)保存在本地存储中,并使用默认查看器打开 [英] Xamarin.Forms save file (pdf) in local storage and open with the default viewer

查看:141
本文介绍了Xamarin.Forms将文件(pdf)保存在本地存储中,并使用默认查看器打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑后可以解决问题

在Android中,我需要将pdf文件下载到文档"文件夹,然后使用默认程序将其打开.我下载了文档并将其存储在Byte数组中.然后我调用此方法:

In Android, I need to download a pdf file to "Documents" folder and open it with the default program. I downloaded the document and stored it in a Byte array. Then I call this method:

    /// <summary>
    /// Save data bytes on "My documents" folder and open
    /// </summary>
    /// <param name="fileName">Filename, for example: "Test.pdf"</param>
    /// <param name="data">Array of bytes to save</param>
    /// <returns>True if success or false if error</returns>
    public bool SaveAndOpen(string fileName, byte[] data)
    {
        try
        {
            // Get my documents path
            string filePath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);
            // Combine with filename
            string fullName = Path.Combine(filePath, fileName);

            // If the file exist on device delete it
            if (File.Exists(fullName))
            {
                // Note: In the second run of this method, the file exists
                File.Delete(fullName);
            }

            // Write bytes on "My documents"
            File.WriteAllBytes(fullName, data);

            // Launch file as process
            Process.Start(fullName);

            return true;
        }
        catch (Exception ex)
        {
            Console.WriteLine("ERROR: " + ex.Message + ex.StackTrace);
            return false;
        }
    }

问题是使用默认的pdf阅读器打开pdf文档.

The problem is to open the pdf document with the default pdf reader.

"Process.Start(fullName);"行引发异常

The line "Process.Start(fullName);" throws an exception

System.ComponentModel.Win32Exception(0x80004005):访问被拒绝

System.ComponentModel.Win32Exception (0x80004005): Access denied

感谢您的时间!

推荐答案

我找到了一种保存和打开文件的方法:

I found a way to save and open the file:

    /// <summary>
    /// Save data bytes on "My documents" folder and open
    /// </summary>
    /// <param name="fileName">Filename, for example: "Test.pdf"</param>
    /// <param name="data">Array of bytes to save</param>
    /// <returns>True if success or false if error</returns>
    public bool SaveAndOpen(string fileName, byte[] data)
    {
        try
        {
            // Get my downloads path
            string filePath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);

            // Combine with filename
            string fullName = Path.Combine(filePath, fileName);

            // If the file exist on device delete it
            if (File.Exists(fullName))
            {
                // Note: In the second run of this method, the file exists
                File.Delete(fullName);
            }

            // Write bytes on "My documents"
            File.WriteAllBytes(fullName, data);

            // Get the uri for the saved file
            Android.Net.Uri file = Android.Support.V4.Content.FileProvider.GetUriForFile(
                this,
                this.PackageName + ".fileprovider",
                new Java.IO.File(fileName));
            Intent intent = new Intent(Intent.ActionView);
            intent.SetDataAndType(file, "application/pdf");
            intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask | ActivityFlags.GrantReadUriPermission | ActivityFlags.NewTask);
            this.ApplicationContext.StartActivity(intent);

            return true;
        }
        catch (Exception ex)
        {
            Console.WriteLine("ERROR: " + ex.Message + ex.StackTrace);
            return false;
        }
    }

需要在运行时请求权限.我使用了Nuget上的Plugin.Permisions:

It's needed to request the permissions at runtime. I used Plugin.Permisions available on Nuget:

    Plugin.Permissions.PermissionsImplementation.Current.RequestPermissionsAsync(
         new Plugin.Permissions.Abstractions.Permission[]
         {
             Plugin.Permissions.Abstractions.Permission.Storage,
             Plugin.Permissions.Abstractions.Permission.MediaLibrary
         });

还要在AndroidManifest.xml文件中添加一个提供程序:

Also add a provider in the AndroidManifest.xml file:

<application android:label="My app" android:icon="@mipmap/icon">
    <provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.fileprovider" android:exported="false" android:grantUriPermissions="true">
        <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"></meta-data>
    </provider>
</application>

在同一AndroidManifest中添加以下项的权限:

In the same AndroidManifest add permisions for:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS" />

并在Resources/xml/file_paths.xml中添加外部路径

And add an external path in Resources/xml/file_paths.xml

<external-path name="external_files" path="."/>

不知道我是否不需要权限,但是可以用这种方式工作.

Don't know if I have not needed permissions, but with this way works.

这篇关于Xamarin.Forms将文件(pdf)保存在本地存储中,并使用默认查看器打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆