【问题标题】:Attempting to read from SD card throws UnauthorizedAccessException尝试从 SD 卡读取会引发 UnauthorizedAccessException
【发布时间】:2015-10-05 11:37:47
【问题描述】:

我正在使用 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 卡的权限?

谢谢!

【问题讨论】:

标签: android xamarin xamarin.android android-permissions


【解决方案1】:

问题是由这一行引起的:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-25
    相关资源
    最近更新 更多