首页 > 解决方案 > 字符串到 java.io.file

问题描述

我是 Xamarin 的新手,我正在尝试从设备打开文件。我收到这个错误

FilePath 是一个包含文件路径的字符串。有没有办法在 C# 中将字符串转换为 java.io.file。

 var FilePath= Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/newfolder" + "/example.pdf";
 Intent intent = new Intent(Intent.ActionView, Android.Net.Uri.FromFile(filePath));
 intent.SetDataAndType(Android.Net.Uri.FromFile(f), "application/msword");
 StartActivity(intent);

标签: c#xamarinxamarin.android

解决方案


这是我的解决方案,您可以使用 WebClient(与 android 相同)下载报告。下载后向用户显示自定义通知。当用户点击通知时,在设备默认应用程序中打开报告(例如:.pdf => pdf 阅读器)。用于Java.IO.File获取保存的报告 uri。

        var ReportAbsolutePath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/Folder";
        Directory.CreateDirectory(ReportAbsolutePath);

        try
        {
            string reportSavedPath = ReportAbsolutePath + "/ReportName.pdf";
            var fileUri = Android.Net.Uri.FromFile(new Java.IO.File(reportSavedPath));

            WebClient webClient = new WebClient();
            webClient.DownloadFileCompleted += (object sender, AsyncCompletedEventArgs e) =>
            {
                Intent intent = new Intent(Intent.ActionView);
                intent.SetDataAndType(fileUri, mimeType);

                var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;

                var notification = new Notification(Resource.Drawable.app_icon, "Title");
                notification.Flags = NotificationFlags.AutoCancel;
                notification.SetLatestEventInfo(this, "title", "desc", 
                PendingIntent.GetActivity(this, 0, mIntent, 0));
                notificationManager.Notify(1, notification);


                ShowToastMessage("Report downloaded successfully.");
            };
            webClient.DownloadFileAsync(new Uri(reportUrl), reportSavedPath);
        }
        catch (Exception ex)
        {
            ShowToastMessage("Error occurred while downloading the report");
        }

推荐阅读