尝试从SD卡读取会抛出UnauthorizedAccessException

时间:2015-10-05 11:37:47

标签: android xamarin xamarin.android android-permissions

我正在使用Xamarin构建Android应用程序,并且需要允许用户从他们的设备中选择JPEG图像并上传它。这个过程涉及几个不同的类,涉及很多检查,我将在这里排除,但这是它的要点:

private void ChooseImage()
{
  // Open the image picker
  Intent intent = new Intent(Intent.ActionGetContent);
  intent.SetType("image/jpg");
  _activity.StartActivityForResult(intent, (int)ImageRequest.ChooseImage);
}

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
  base.OnActivityResult(requestCode, resultCode, data);

  string path;

  Android.Net.Uri selectedImage = data.Data;
  string[] filePathColumn = { MediaStore.MediaColumns.Data, MediaStore.MediaColumns.DisplayName };

  using (ICursor cursor = ContentResolver.Query(selectedImage, filePathColumn, null, null, null))
  {
    // Get the path to the selected file
    path = cursor.GetString(columnIndex);
  }

  using (FileStream fs = File.Open(path, FileMode.Open))
  {
    byte[] bytes = new byte[fs.Length];

    // This throws an UnauthorizedAccessException
    fs.Read(bytes, 0, Convert.ToInt32(fs.Length));

    UploadImage(bytes);
  }
}

我还拥有在AndroidManifest中设置的必要权限:

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

如果用户在SD卡而不是本地存储上选择图像,则此代码会引发以下异常:

System.UnauthorizedAccessException: Access to the path "/storage/sdcard1/[user selected image].jpg" is denied.

所以... 为什么我没有权限从SD卡读取数据?

谢谢!

1 个答案:

答案 0 :(得分:3)

问题是由这一行引起的:

using (FileStream fs = File.Open(path, FileMode.Open))

我应该添加第三个参数来指定读取模式而不是默认的读/写:

using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read))