如何在Xamarin.Android中使用C#查找所选图像的文件路径?

问题描述 投票:0回答:1

我正在使用Xamarin.Android平台开发Android应用程序。我正在将此部署到我的设备上。我正在尝试从我的Android图库中获取所选图像的文件路径,但我正在获取System.IO.DirectoryNotFoundException: 'Could not find a part of the path "/document/image:2547".'

我已经为此研究了解决方案,但是这些解决方案都不适合我的情况。

我将排除一些不需要显示的代码。

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
    Android.Net.Uri uri = data.Data;
    string path = uri.Path;
    ImageView imageView = new ImageView(this);
    imageView.SetImageURI(uri);
    Blob.UploadFileInBlob(path);
}
public static class Blob
{
    public static async void UploadFileInBlob(string path)
    {
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse("[string here]");
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        CloudBlobContainer container = blobClient.GetContainerReference("images");
        await container.CreateIfNotExistsAsync();
        CloudBlockBlob blockBlob = container.GetBlockBlobReference("imageblob.jpg");
        await blockBlob.UploadFromFileAsync(@path);
    }
}

我希望根据图像文件路径将图像文件上传到Block Blob。但是,我收到了System.IO.DirectoryNotFoundException: 'Could not find a part of the path "/document/image:2547".'错误。选择图像后,图像本身仍会显示在应用程序中。

c# xamarin xamarin.android
1个回答
0
投票

您可以引用我的另一个线程here,它应该对您有所帮助。主要代码如下:

方法OnActivityResult

protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
    base.OnActivityResult(requestCode, resultCode, data);
        if (resultCode == Result.Canceled)
        {
            Finish();
        }
        else
        {
            try
            {
            var _uri = data.Data;
            var filePath = IOUtil.getPath(this, _uri);

            if (string.IsNullOrEmpty(filePath))
                filePath = _uri.Path;

            var file = IOUtil.readFile(filePath);// here we can get byte array
        }
            catch (Exception readEx)
            {
                System.Diagnostics.Debug.Write(readEx);
            }
            finally
            {
                Finish();
            }
    }
}

IOUtil.cs

public class IOUtil
{
  public static string getPath(Context context, Android.Net.Uri uri)
{
    bool isKitKat = Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat;

    // DocumentProvider
    if (isKitKat && DocumentsContract.IsDocumentUri(context, uri))
    {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri))
        {
            var docId = DocumentsContract.GetDocumentId(uri);
            string[] split = docId.Split(':');
            var type = split[0];

            if ("primary".Equals(type, StringComparison.OrdinalIgnoreCase))
            {
                return Android.OS.Environment.ExternalStorageDirectory + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri))
        {

            string id = DocumentsContract.GetDocumentId(uri);
            Android.Net.Uri contentUri = ContentUris.WithAppendedId(
                    Android.Net.Uri.Parse("content://downloads/public_downloads"), long.Parse(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri))
        {
            var docId = DocumentsContract.GetDocumentId(uri);
            string[] split = docId.Split(':');
            var type = split[0];

            Android.Net.Uri contentUri = null;
            if ("image".Equals(type))
            {
                contentUri = MediaStore.Images.Media.ExternalContentUri;
            }
            else if ("video".Equals(type))
            {
                contentUri = MediaStore.Video.Media.ExternalContentUri;
            }
            else if ("audio".Equals(type))
            {
                contentUri = MediaStore.Audio.Media.ExternalContentUri;
            }

            var selection = "_id=?";
            var selectionArgs = new string[] {
                split[1]
            };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".Equals(uri.Scheme, StringComparison.OrdinalIgnoreCase))
    {
        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".Equals(uri.Scheme, StringComparison.OrdinalIgnoreCase))
    {
        return uri.Path;
    }

    return null;
}

public static string getDataColumn(Context context, Android.Net.Uri uri, string selection,
string[] selectionArgs)
{

    ICursor cursor = null;
    var column = "_data";
    string[] projection = {
        column
    };

    try
    {
        cursor = context.ContentResolver.Query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.MoveToFirst())
        {
            int column_index = cursor.GetColumnIndexOrThrow(column);
            return cursor.GetString(column_index);
        }
    }
    finally
    {
        if (cursor != null)
            cursor.Close();
    }
    return null;
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 */
public static bool isExternalStorageDocument(Android.Net.Uri uri)
{
    return "com.android.externalstorage.documents".Equals(uri.Authority);
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */
public static bool isDownloadsDocument(Android.Net.Uri uri)
{
    return "com.android.providers.downloads.documents".Equals(uri.Authority);
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */
public static bool isMediaDocument(Android.Net.Uri uri)
{
    return "com.android.providers.media.documents".Equals(uri.Authority);
}

public static byte[] readFile(string file)
{
    try
    {
        return readFile(new File(file));
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.Write(ex);
        return new byte[0];
    }
 }

 public static byte[] readFile(File file)
 {
    // Open file
    var f = new RandomAccessFile(file, "r");

    try
    {
        // Get and check length
        long longlength = f.Length();
        var length = (int)longlength;

        if (length != longlength)
            throw new IOException("Filesize exceeds allowed size");
        // Read file and return data
        byte[] data = new byte[length];
        f.ReadFully(data);
        return data;
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.Write(ex);
        return new byte[0];
    }
    finally
    {
        f.Close();
    }
 }
}
© www.soinside.com 2019 - 2024. All rights reserved.