【发布时间】: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