字符串到java.io.file

时间:2018-06-10 16:23:40

标签: c# xamarin xamarin.android

我是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);

2 个答案:

答案 0 :(得分:1)

这是我的解决方案,您可以使用WebClient下载报告(与android相同)。下载后向用户显示自定义通知。当用户点击通知时,在设备默认应用程序中打开报告(例如:.pdf => pdf reader)。使用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");
        }

答案 1 :(得分:0)

  

有没有办法在C#中将字符串转换为java.io.file。

您可以使用File类。

例如:

        var FilePath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/newfolder" + "/example.pdf";
        File file = new File(FilePath);
        Intent intent = new Intent(Intent.ActionView, Android.Net.Uri.FromFile(file));