Xamarin在API 23上表示ENOENT(没有这样的文件或目录)

时间:2016-08-10 15:04:05

标签: android xamarin.android xamarin.forms

我正在使用以下代码从我的Xamarin Forms Android项目中的流中下载和打开文件。这适用于所有API< 23。

在API 23中,我在行上得到以下异常:FileOutputStream outStream = new FileOutputStream(file);

{Java.IO.FileNotFoundException:/storage/emulated/0/pgmdoc/myiamge.jpg:open failed:ENOENT(没有这样的文件或目录)---> Android.Systems.ErrnoException:open failed:ENOENT(没有这样的文件或目录)

[assembly: Xamarin.Forms.Dependency(typeof(SaveAndLoad_Android))]
namespace MyProgram.Droid
{
public class SaveAndLoad_Android : MYProgramFiles.ISaveAndLoad
    {
        public async Task SaveFileAsync(string fileName, String contentType, MemoryStream stream)
        {
            string root = null;
            if (Android.OS.Environment.IsExternalStorageEmulated)
            {
                root = Android.OS.Environment.ExternalStorageDirectory.ToString();
            }
            else
                root = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);

            Java.IO.File myDir = new Java.IO.File(root + "/pgmdoc");
            if (!myDir.Exists())
            {
                myDir.Mkdir();
            }

            Java.IO.File file = new Java.IO.File(myDir, fileName);


            try
            {
                FileOutputStream outStream = new FileOutputStream(file);
                outStream.Write(stream.ToArray());
                outStream.Close();
            }
            catch (Exception e)
            {
                //error happenin on
                //FileOutputStream outStream = new FileOutputStream(file);
            }
            if (file.Exists())
            {
                Android.Net.Uri path = Android.Net.Uri.FromFile(file);
                string extension = Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(path.ToString());
                string mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);
                Intent intent = new Intent(Intent.ActionView);
                intent.SetDataAndType(path, mimeType);
                Forms.Context.StartActivity(Intent.CreateChooser(intent, "Select App"));
            }
        }
    }
}

在我的Android Manafest中,我指定了权限: android.permission.READ_EXTERNAL_STORAGE android.permission.WRITE_EXTERNAL_STORAGE

感谢任何帮助

1 个答案:

答案 0 :(得分:0)

Pztar是对的。

这里有一个有用的示例供有需要的人使用:https://developer.xamarin.com/samples/monodroid/android-m/RuntimePermissions/

如果您使用的是依赖服务,我强烈建议使用当前的活动插件和权限插件。

https://github.com/jamesmontemagno/CurrentActivityPlugin https://github.com/jamesmontemagno/PermissionsPlugin