Пример #1
0
        static string ResolvePhysicalPath(AndroidUri uri)
        {
            if (Platform.HasApiLevelKitKat && DocumentsContract.IsDocumentUri(Platform.AppContext, uri))
            {
                var resolved = ResolveDocumentPath(uri);
                if (File.Exists(resolved))
                {
                    return(resolved);
                }
            }

            if (uri.Scheme.Equals(UriSchemeContent, StringComparison.OrdinalIgnoreCase))
            {
                var resolved = ResolveContentPath(uri);
                if (File.Exists(resolved))
                {
                    return(resolved);
                }
            }
            else if (uri.Scheme.Equals(UriSchemeFile, StringComparison.OrdinalIgnoreCase))
            {
                var resolved = uri.Path;
                if (File.Exists(resolved))
                {
                    return(resolved);
                }
            }

            return(null);
        }
        public async void Start()
        {
            try
            {
                fileData = await CrossFilePicker.Current.PickFile();
            }
            catch (Exception ex)
            {
                Logger.Log("Error", ex.Message);
            }


            string path = null;

            if (fileData != null)
            {
                Android.Net.Uri potentialUri = Android.Net.Uri.Parse(fileData.FilePath);
                if (DocumentsContract.IsDocumentUri(context, potentialUri))
                {
                    string docId = DocumentsContract.GetDocumentId(potentialUri);
                    path = "/storage/" + docId.Replace(':', '/');
                }
                else
                {
                    path = fileData.FilePath;
                }
            }

            Finished.Invoke(this, new FinishedEventArgs()
            {
                PathToFile = path
            });
        }
Пример #3
0
        public static String GetPath(Context context, Android.Net.Uri uri)
        {
            // DocumentProvider
            if (DocumentsContract.IsDocumentUri(context, uri))
            {
                // ExternalStorageProvider
                if ("com.android.externalstorage.documents".Equals(uri.Authority, StringComparison.OrdinalIgnoreCase))
                {
                    string   docId = DocumentsContract.GetDocumentId(uri);
                    string[] split = docId.Split(":");
                    string   type  = split[0];

                    if ("primary".Equals(type, StringComparison.OrdinalIgnoreCase))
                    {
                        return(System.IO.Path.Combine(Android.OS.Environment.ExternalStorageDirectory.Path, split[1]));
                    }
                    // TODO handle non-primary volumes
                }
                // DownloadsProvider
                else if ("com.android.providers.downloads.documents".Equals(uri.Authority, StringComparison.OrdinalIgnoreCase))
                {
                    string id         = DocumentsContract.GetDocumentId(uri);
                    var    contentUri = ContentUris.WithAppendedId(Android.Net.Uri.Parse("content://downloads/public_downloads"), long.Parse(id));

                    return(GetDataColumn(context, contentUri, null, null));
                }
                // MediaProvider
                else if ("com.android.providers.media.documents".Equals(uri.Authority, StringComparison.OrdinalIgnoreCase))
                {
                    string   docId = DocumentsContract.GetDocumentId(uri);
                    string[] split = docId.Split(":");
                    string   type  = split[0];

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

                    string   selection     = "_id=?";
                    string[] 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);
        }
Пример #4
0
        /* Check whether this uri represent a document or not. */
        private bool isDocumentUri(Context ctx, Uri uri)
        {
            bool ret = false;

            if (ctx != null && uri != null)
            {
                ret = DocumentsContract.IsDocumentUri(ctx, uri);
            }
            return(ret);
        }
Пример #5
0
        // https://stackoverflow.com/a/39388941
        public static string GetPathFromUri(Context context, Uri uri)
        {
            string getDataColumn(Uri uri, string selection, string[] selectionArgs)
            {
                using ICursor cursor = context.ContentResolver.Query(uri, new string[] { "_data" }, selection, selectionArgs, null);
                if (cursor != null && cursor.MoveToFirst())
                {
                    return(cursor.GetString(cursor.GetColumnIndexOrThrow("_data")));
                }
                else
                {
                    return(null);
                }
            }

            bool isKitKat = Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat;

            if (isKitKat && DocumentsContract.IsDocumentUri(context, uri))
            {
                if (uri.Authority == "com.android.externalstorage.documents")
                {
                    string   docId = DocumentsContract.GetDocumentId(uri);
                    string[] split = docId.Split(":");
                    string   type  = split[0];

                    if (type.Equals("primary", StringComparison.InvariantCultureIgnoreCase))
                    {
                        return(context.GetExternalFilesDir(null) + "/" + split[1]);
                        //Android.OS.Environment.ExternalStorageDirectory + "/" + split[1]; // replace with non deprecated alternative
                    }
                    // TODO non primary volumes
                }
                else if (uri.Authority == "com.android.providers.downloads.documents")
                {
                    return(getDataColumn(ContentUris.WithAppendedId(Uri.Parse("content://downloads/public_downloads"), long.Parse(DocumentsContract.GetDocumentId(uri))), null, null));
                }
                else if (uri.Authority == "com.android.providers.media.documents")
                {
                    return(getDataColumn(MediaStore.Images.Media.ExternalContentUri, "_id=?", new[] { DocumentsContract.GetDocumentId(uri).Split(":")[1] }));
                }
            }
            else if (uri.Scheme.Equals("content", StringComparison.InvariantCultureIgnoreCase))
            {
                return(uri.Authority == "com.google.android.apps.photos.content"
                                        ? uri.LastPathSegment
                                        : getDataColumn(uri, null, null));
            }
            else if (uri.Scheme.Equals("file", StringComparison.InvariantCultureIgnoreCase))
            {
                return(uri.Path);
            }

            return(null);
        }
Пример #6
0
        static bool IsVirtualFile(AndroidUri uri)
        {
            if (!DocumentsContract.IsDocumentUri(Platform.AppContext, uri))
            {
                return(false);
            }

            var value = GetColumnValue(uri, DocumentsContract.Document.ColumnFlags);

            if (!string.IsNullOrEmpty(value) && int.TryParse(value, out var flagsInt))
            {
                var flags = (DocumentContractFlags)flagsInt;
                return(flags.HasFlag(DocumentContractFlags.VirtualDocument));
            }

            return(false);
        }
Пример #7
0
        static string ResolvePhysicalPath(AndroidUri uri, bool requireExtendedAccess = true)
        {
            if (uri.Scheme.Equals(UriSchemeFile, StringComparison.OrdinalIgnoreCase))
            {
                // if it is a file, then return directly

                var resolved = uri.Path;
                if (File.Exists(resolved))
                {
                    return(resolved);
                }
            }
            else if (!requireExtendedAccess || !OperatingSystem.IsAndroidVersionAtLeast(29))
            {
                // if this is on an older OS version, or we just need it now

                if (Platform.HasApiLevelKitKat && DocumentsContract.IsDocumentUri(Platform.AppContext, uri))
                {
                    var resolved = ResolveDocumentPath(uri);
                    if (File.Exists(resolved))
                    {
                        return(resolved);
                    }
                }
                else if (uri.Scheme.Equals(UriSchemeContent, StringComparison.OrdinalIgnoreCase))
                {
                    var resolved = ResolveContentPath(uri);
                    if (File.Exists(resolved))
                    {
                        return(resolved);
                    }
                }
            }

            return(null);
        }
Пример #8
0
        //    @TargetApi(Build.VERSION_CODES.KITKAT)
        public static String GetPath(Context context, Android.Net.Uri uri)
        {
            bool isKitKat = Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat; //Build.VERSION_CODES.Kitkat;

            // DocumentProvider
            if (isKitKat && DocumentsContract.IsDocumentUri(context, uri))
            {
                // ExternalStorageProvider
                if (IsExternalStorageDocument(uri))
                {
                    String   docId = DocumentsContract.GetDocumentId(uri);
                    String[] split = docId.Split(":");
                    String   type  = split[0];
                    if ("primary".Equals(type, StringComparison.InvariantCultureIgnoreCase)) //equalsIgnoreCase
                    {
                        return(Android.OS.Environment.GetExternalStoragePublicDirectory(type) + "/" + split[1]);
                    }
                }
                // DownloadsProvider
                else if (IsDownloadsDocument(uri))
                {
                    /*
                     *          final String id = DocumentsContract.getDocumentId(uri);
                     *          final Uri contentUri = ContentUris.withAppendedId(
                     *                  Uri.parse("content://<span id=\"IL_AD1\" class=\"IL_AD\">downloads</span>/public_downloads"), Long.valueOf(id));
                     *          return getDataColumn(context, contentUri, null, null);
                     */
                    String fileName = GetFileName(context, uri);
                    File   downFile = new File(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads), "/" + fileName);
                    return(downFile.AbsolutePath);
                }
                // MediaProvider
                else if (IsMediaDocument(uri))
                {
                    String          docId      = DocumentsContract.GetDocumentId(uri);
                    String[]        split      = docId.Split(":");
                    String          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;
                    }
                    String   selection     = "_id=?";
                    String[] selectionArgs = new String[] {
                        split[1]
                    };
                    return(GetDataColumn(context, contentUri, selection, selectionArgs));
                }
            }
            // MediaStore (and general)
            else if ("content".Equals(uri.Scheme, StringComparison.InvariantCultureIgnoreCase))
            {
                // Return the remote address
                if (IsGooglePhotosUri(uri))
                {
                    return(uri.LastPathSegment);
                }
                return(GetDataColumn(context, uri, null, null));
            }
            // File
            else if ("file".Equals(uri.Scheme, StringComparison.InvariantCultureIgnoreCase))
            {
                return(uri.Path);
            }
            return(null);
        }
        public static string ToPhysicalPath(this Uri uri, Context ctx)
        {
            var isKitkat = Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat;

            var isDocumentUri = DocumentsContract.IsDocumentUri(ctx, uri);
            var isTreeUri     = DocumentsContract.IsTreeUri(uri);

            if (isKitkat && (isDocumentUri || isTreeUri))
            {
                var rootUri = isDocumentUri
                    ? DocumentsContract.GetDocumentId(uri)
                    : DocumentsContract.GetTreeDocumentId(uri);

                if (uri.Authority == "com.android.localstorage.documents")
                {
                    return(rootUri);
                }

                if (uri.Authority == "com.android.externalstorage.documents")
                {
                    var splitDocumentId = rootUri.Split(':');
                    var type            = splitDocumentId[0];

                    if (string.Compare(type, "primary", StringComparison.InvariantCultureIgnoreCase) == 0)
                    {
                        return(Path.Combine(Android.OS.Environment.ExternalStorageDirectory.Path, splitDocumentId[1]));
                    }

                    // Handle non-primary
                    //! TODO: This is absolutely disgusting but android offers no easy way to obtain a path to a directory from an Uri to a directory.
                    //! I'm not even sure this is portable.
                    var contentUri = MediaStore.Files.GetContentUri(type);
                    var cursor     = ctx.ContentResolver.Query(contentUri, null, null, null, null);
                    if (cursor != null && cursor.MoveToFirst())
                    {
                        var path = cursor.GetString(0);
                        cursor.Close();
                        return(path);
                    }
                    else
                    {
                        return("/storage/" + rootUri.Replace(':', '/'));
                    }

                    return(contentUri.ToPhysicalPath(ctx));
                }

                if (uri.Authority == "com.android.providers.downloads.documents")
                {
                    var contentUri = ContentUris.WithAppendedId(Uri.Parse("content://downloads/public_downloads"), long.Parse(rootUri));

                    return(ctx.GetDataColumn(contentUri, MediaStore.MediaColumns.Data, null, null));
                }

                if (uri.Authority == "com.android.providers.media.documents")
                {
                    var splitDocumentId = rootUri.Split(':');
                    var type            = splitDocumentId[0];

                    Uri contentUri = null;

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

                    return(ctx.GetDataColumn(contentUri, MediaStore.MediaColumns.Data, "_id?=", splitDocumentId[1]));
                }
            }
            // MediaStore and general
            else if (uri.Scheme == "content")
            {
                if (uri.Authority == "com.google.android.apps.photos.content")
                {
                    return(uri.LastPathSegment);
                }

                return(ctx.GetDataColumn(uri, MediaStore.MediaColumns.Data, null, null));
            }
            else if (uri.Scheme == "file")
            {
                return(uri.Path);
            }

            return("");
        }
Пример #10
0
        internal static String GetPathFromURI(Context context, Android.Net.Uri uri)
        {
            bool isKitKat = Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat;

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

                    if ("primary".Equals(type, StringComparison.InvariantCultureIgnoreCase))
                    {
                        return(Android.OS.Environment.ExternalStorageDirectory + "/" + split[1]);
                    }
                }
                // 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)Convert.ToDouble(id));

                    return(GetDataColumn(context, contentUri, null, null));
                }
                // MediaProvider
                else if (IsMediaDocument(uri))
                {
                    String   docId = DocumentsContract.GetDocumentId(uri);
                    String[] split = docId.Split(':');
                    String   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;
                    }

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

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

            return(null);
        }
Пример #11
0
        /// <summary>
        /// Tries to find a file system path for given Uri. Note that this isn't always possible,
        /// since the content referenced by the Uri may not be stored on a file system, but is
        /// returned by the responsible app by using a ContentProvider. In this case, the method
        /// returns null, and access to the content is only possible by opening a stream.
        /// </summary>
        /// <param name="context">Android context to access content resolver</param>
        /// <param name="uri">Uri to use</param>
        /// <returns>full file system path, or null</returns>
        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(context.GetExternalFilesDir(null) + "/" + split[1]);
                    }

                    // TODO handle non-primary volumes
                }
                else if (IsDownloadsDocument(uri))
                {
                    // android 11 使用原来的方法已无法获取,采用先获取文件名,再合成路径
                    string fileName = GetFileName(context, uri);
                    if (!string.IsNullOrEmpty(fileName))
                    {
                        return(System.IO.Path.Combine(GetDownloadsPath(), fileName));
                    }

                    // DownloadsProvider
                    string id = DocumentsContract.GetDocumentId(uri);

                    if (!string.IsNullOrEmpty(id) && id.StartsWith("raw:"))
                    {
                        return(id.Substring(4));
                    }

                    string[] contentUriPrefixesToTry = new string[]
                    {
                        "content://downloads/public_downloads",
                        "content://downloads/my_downloads",
                        "content://downloads/all_downloads",
                    };

                    foreach (string contentUriPrefix in contentUriPrefixesToTry)
                    {
                        Android.Net.Uri contentUri = ContentUris.WithAppendedId(
                            Android.Net.Uri.Parse(contentUriPrefix), long.Parse(id));

                        try
                        {
                            var path = GetDataColumn(context, contentUri, null, null);
                            if (path != null)
                            {
                                return(path);
                            }
                        }
                        catch (Exception)
                        {
                            // ignore exception; path can't be retrieved using ContentResolver
                        }
                    }
                }
                else if (IsMediaDocument(uri))
                {
                    // MediaProvider
                    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)
            if (IsMediaStore(uri.Scheme))
            {
                return(GetDataColumn(context, uri, null, null));
            }
            else if ("file".Equals(uri.Scheme, StringComparison.OrdinalIgnoreCase))
            {
                return(uri.Path);
            }

            return(null);
        }
Пример #12
0
        public static string GetActualPathFromFile(Android.Net.Uri uri, Context context)
        {
            bool isKitKat = Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat;

            if (isKitKat && DocumentsContract.IsDocumentUri(context, uri))
            {
                // ExternalStorageProvider
                if (isExternalStorageDocument(uri))
                {
                    string docId = DocumentsContract.GetDocumentId(uri);

                    char[] chars = { ':' };
                    string[] split = docId.Split(chars);
                    string type = split[0];

                    if ("primary".Equals(type, StringComparison.OrdinalIgnoreCase))
                    {
                        return Android.OS.Environment.ExternalStorageDirectory + "/" + split[1];
                    }
                }
                // 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));

                    //System.Diagnostics.Debug.WriteLine(contentUri.ToString());

                    return getDataColumn(context, contentUri, null, null);
                }
                // MediaProvider
                else if (isMediaDocument(uri))
                {
                    String docId = DocumentsContract.GetDocumentId(uri);

                    char[] chars = { ':' };
                    String[] split = docId.Split(chars);

                    String 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;
                    }

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

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

                // Return the remote address
                if (isGooglePhotosUri(uri))
                    return uri.LastPathSegment;

                return getDataColumn(context, uri, null, null);
            }
            // File
            else if ("file".Equals(uri.Scheme, StringComparison.OrdinalIgnoreCase))
            {
                return uri.Path;
            }

            return null;
        }
        public static string GetPath(Context context, Uri uri)
        {
            bool isKitKat = Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat;

            // DocumentProvider (da Kitkat in su)
            if (isKitKat && DocumentsContract.IsDocumentUri(context, uri))
            {
                // ExternalStorageProvider
                if (IsExternalStorageDocument(uri))
                {
                    string   docId = DocumentsContract.GetDocumentId(uri);
                    string[] split = docId.Split(":");
                    string   type  = split[0];

                    if (type.Equals("primary", System.StringComparison.InvariantCultureIgnoreCase))
                    {
                        if (split.Length > 1)
                        {
                            return(System.IO.Path.Combine(ExtractExternalStorageFolderRoot(context.GetExternalFilesDir(null).AbsolutePath), split[1]));
                        }
                        else
                        {
                            return(ExtractExternalStorageFolderRoot(context.GetExternalFilesDir(null).AbsolutePath) + Java.IO.File.Separator);
                        }
                    }

                    Java.IO.File[] externalPaths = Android.App.Application.Context.GetExternalFilesDirs(null);
                    if (externalPaths.Length <= 1)
                    {
                        throw new System.Exception("Unable to access to the external storage");
                    }

                    // SDCard è in posizione 1
                    return(System.IO.Path.Combine(ExtractExternalStorageFolderRoot(externalPaths[1].AbsolutePath), split[1]));
                }
                // DownloadsProvider
                else if (IsDownloadsDocument(uri))
                {
                    string id         = DocumentsContract.GetDocumentId(uri);
                    Uri    contentUri = ContentUris.WithAppendedId(
                        Uri.Parse("content://downloads/public_downloads"), long.Parse(id));

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

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

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

                    return(GetDataColumn(context, contentUri, selection, selectionArgs));
                }
            }
            // MediaStore (generale)
            else if (uri.Scheme.Equals("content", System.StringComparison.InvariantCultureIgnoreCase))
            {
                if (IsGooglePhotosUri(uri))
                {
                    return(uri.LastPathSegment);
                }

                return(GetDataColumn(context, uri, null, null));
            }
            // File
            else if (uri.Scheme.Equals("file", System.StringComparison.InvariantCultureIgnoreCase))
            {
                return(uri.Path);
            }

            throw new System.Exception("Unable to compute the real path of uri: " + uri.Path);
        }
Пример #14
0
        //MaX Add
        public string getPathFromUri(Context context, Android.Net.Uri uri)
        {
            if (uri == null)
            {
                return(null);
            }
            // 判斷是否為Android 4.4之後的版本
            bool after44 = (Int32)Build.VERSION.SdkInt >= 19;

            if (after44 && DocumentsContract.IsDocumentUri(context, uri))
            {
                // 如果是Android 4.4之後的版本,而且屬於文件URI
                string authority = uri.Authority;

                // 判斷Authority是否為本地端檔案所使用的
                if ("com.android.externalstorage.documents".Equals(authority))
                {
                    // 外部儲存空間
                    string   docId  = DocumentsContract.GetDocumentId(uri);
                    string[] divide = docId.Split(':');
                    string   type   = divide[0];

                    if ("primary".Equals(type))
                    {
                        return(Android.OS.Environment.ExternalStorageDirectory + "/" + divide[1]);
                    }
                }
                else if ("com.android.providers.downloads.documents".Equals(authority))
                {
                    // 下載目錄
                    string          docId       = DocumentsContract.GetDocumentId(uri);
                    Android.Net.Uri downloadUri = ContentUris.WithAppendedId(Android.Net.Uri.Parse("content://downloads/public_downloads"), Long.ParseLong(docId));
                    return(queryAbsolutePath(context, downloadUri));
                }
                else if ("com.android.providers.media.documents".Equals(authority))
                {
                    // 圖片、影音檔案
                    string          docId    = DocumentsContract.GetDocumentId(uri);
                    string[]        divide   = docId.Split(':');
                    string          type     = divide[0];
                    Android.Net.Uri mediaUri = null;
                    if ("image".Equals(type))
                    {
                        mediaUri = MediaStore.Images.Media.ExternalContentUri;
                    }
                    else if ("video".Equals(type))
                    {
                        mediaUri = MediaStore.Video.Media.ExternalContentUri;
                    }
                    else if ("audio".Equals(type))
                    {
                        mediaUri = MediaStore.Audio.Media.ExternalContentUri;
                    }
                    else
                    {
                        return(null);
                    }
                    mediaUri = ContentUris.WithAppendedId(mediaUri, Long.ParseLong(divide[1]));
                    return(queryAbsolutePath(context, mediaUri));
                }
            }
            else
            {
                // 如果是一般的URI
                string scheme = uri.Scheme;
                string path   = null;
                if ("content".Equals(scheme))
                {
                    // 內容URI
                    path = queryAbsolutePath(context, uri);
                }
                else if ("file".Equals(scheme))
                {
                    // 檔案URI
                    path = uri.Path;
                }
                return(path);
                //return createFileObjFromPath(path, mustCanRead);
            }
            return(null);
        }
Пример #15
0
        private static string getRealPathFromUri_AboveApi19(Context context, Android.Net.Uri uri)
        {
            if (DocumentsContract.IsDocumentUri(context, uri))
            {
                if (isExternalStorageDocument(uri))
                {
                    var docId = DocumentsContract.GetDocumentId(uri);
                    var split = docId.Split(":");
                    var type  = split[0];
                    if ("primary" == (type))
                    {
                        return(Environment.ExternalStorageDirectory + "/" + split[1]);
                    }
                }
                else if (isDownloadsDocument(uri))
                {
                    var id         = DocumentsContract.GetDocumentId(uri);
                    var contentUri = ContentUris.WithAppendedId(
                        Uri.Parse("content://downloads/public_downloads"), long.Parse(id));

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

                    Uri contentUri;
                    if ("image" == (type))
                    {
                        contentUri = MediaStore.Images.Media.ExternalContentUri;
                    }
                    else if ("video" == (type))
                    {
                        contentUri = MediaStore.Video.Media.ExternalContentUri;
                    }
                    else if ("audio" == (type))
                    {
                        contentUri = MediaStore.Audio.Media.ExternalContentUri;
                    }
                    else
                    {
                        contentUri = MediaStore.Files.GetContentUri("external");
                    }

                    var      selection     = "_id=?";
                    string[] selectionArgs = new string[] { split[1] };
                    return(getDataColumn(context, contentUri, selection, selectionArgs));
                }
            }
            else if ("content" == (uri.Scheme))
            {
                return(getDataColumn(context, uri, null, null));
            }
            else if ("file" == (uri.Scheme))
            {
                return(uri.Path);
            }
            return(null);
        }
Пример #16
0
        private static string GetRealPathFromURI_API19(Context context, Uri uri)
        {
            var isKitKat = Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat;

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

                    if (string.Equals(type, "primary", StringComparison.OrdinalIgnoreCase))
                    {
                        return(Environment.ExternalStorageDirectory + "/" + split[1]);
                    }
                }
                else if (IsDownloadsDocument(uri))
                {
                    var id         = DocumentsContract.GetDocumentId(uri);
                    var contentUri = ContentUris.WithAppendedId(
                        Uri.Parse("content://downloads/public_downloads"), long.Parse(id));

                    return(GetDataColumn(context, contentUri, null, null));
                }
                else if (IsMediaDocument(uri))
                {
                    var docId = DocumentsContract.GetDocumentId(uri);
                    var split = docId.Split(':');
                    var type  = split[0];

                    Uri contentUri = null;
                    switch (type)
                    {
                    case "image":
                        contentUri = MediaStore.Images.Media.ExternalContentUri;
                        break;

                    case "video":
                        contentUri = MediaStore.Video.Media.ExternalContentUri;
                        break;

                    case "audio":
                        contentUri = MediaStore.Audio.Media.ExternalContentUri;
                        break;
                    }

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

                    return(GetDataColumn(context, contentUri, selection, selectionArgs));
                }
            }
            else if (string.Equals("content", uri.Scheme, StringComparison.OrdinalIgnoreCase))
            {
                return(IsGooglePhotoUri(uri) ? uri.LastPathSegment : GetDataColumn(context, uri, null, null));
            }
            else if (string.Equals("file", uri.Scheme, StringComparison.OrdinalIgnoreCase))
            {
                return(uri.Path);
            }

            return(null);
        }
Пример #17
0
        // found API version variations at http://hmkcode.com/android-display-selected-image-and-its-real-path/
        //        private string GetPathToImageApi19(Uri uri)
        //        {
        //            string path = uri.Path;
        //            if (!DocumentsContract.IsDocumentUri(Application.Context, uri))
        //                return path;
        //            string wholeId = DocumentsContract.GetDocumentId(uri);
        //            string id = wholeId.Split(new[] {':'})[1];
        //            string[] column = {MediaStore.Images.Media.InterfaceConsts.Data};
        //            string sel = MediaStore.Images.Media.InterfaceConsts.Id + "=?";
        //            using (var cursor = ContentResolver.Query(MediaStore.Images.Media.ExternalContentUri, column, sel,
        //                new string[] {id}, null))
        //            {
        //                int columnIndex = cursor.GetColumnIndex(column[0]);
        //                if (cursor.MoveToFirst())
        //                    path = cursor.GetString(columnIndex);
        //                cursor.Close();
        //            }
        //            return path;
        //        }
        //
        //        private string GetPathToImage(Uri uri)
        //        {
        //            string path = uri.Path;
        //            // The projection contains the columns we want to return in our query.
        //            string[] projection = new[] { MediaStore.Images.Media.InterfaceConsts.Data };
        //            using (var cursor = ContentResolver.Query(uri, projection, null, null, null))
        //            {
        //                if (cursor != null && cursor.MoveToFirst())
        //                {
        //                    int columnIndex = cursor.GetColumnIndexOrThrow(Android.Provider.MediaStore.Images.Media.InterfaceConsts.Data);
        //                    path = cursor.GetString(columnIndex);
        //                }
        //            }
        //            return path;
        //        }

        // found this method at http://stackoverflow.com/questions/31715181/android-get-image-path
        // and converted it for Xamarin.  Covers more options than the previous and seems to be working well.
        public string GetPath(Uri uri)
        {
            bool isKitKat = Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat;

            // DocumentProvider
            if (isKitKat && DocumentsContract.IsDocumentUri(Application.Context, uri))
            {
                // ExternalStorageProvider
                if (IsExternalStorageDocument(uri))
                {
                    string   docId = DocumentsContract.GetDocumentId(uri);
                    string[] split = docId.Split(new char[] { ':' });
                    string   type  = split[0];
                    if (type.ToLower() == "primary")
                    {
                        return(Environment.ExternalStorageDirectory + "/" + split[1]);
                    }
                }
                // DownloadsProvider
                else if (IsDownloadsDocument(uri))
                {
                    string id         = DocumentsContract.GetDocumentId(uri);
                    Uri    contentUri = ContentUris.WithAppendedId(Uri.Parse("content://downloads/public_downloads"), long.Parse(id));
                    return(GetDataColumn(Application.Context, contentUri, null, null));
                }
                // MediaProvider
                else if (IsMediaDocument(uri))
                {
                    string   docId      = DocumentsContract.GetDocumentId(uri);
                    string[] split      = docId.Split(new char[] { ':' });
                    string   type       = split[0];
                    Uri      contentUri = null;
                    if (type == "image")
                    {
                        contentUri = MediaStore.Images.Media.ExternalContentUri;
                    }
                    else if (type == "video")
                    {
                        contentUri = MediaStore.Video.Media.ExternalContentUri;
                    }
                    else if (type == "audio")
                    {
                        contentUri = MediaStore.Audio.Media.ExternalContentUri;
                    }
                    string   selection     = "_id=?";
                    string[] selectionArgs = new String[] { split[1] };
                    return(GetDataColumn(Application.Context, contentUri, selection, selectionArgs));
                }
            }
            // MediaStore (and general)
            else if (uri.Scheme.ToLower() == "content")
            {
                // Return the remote address
                if (IsGooglePhotosUri(uri))
                {
                    return(uri.LastPathSegment);
                }
                return(GetDataColumn(Application.Context, uri, null, null));
            }
            // File
            else if (uri.Scheme.ToLower() == "file")
            {
                return(uri.Path);
            }
            return(null);
        }
Пример #18
0
        /// <summary>
        /// Main feature. Return actual path for file from uri.
        /// </summary>
        /// <param name="uri">File's uri</param>
        /// <param name="context">Current context</param>
        /// <returns>Actual path</returns>
        public static string GetActualPathForFile(global::Android.Net.Uri uri, Context context)
        {
            bool isKitKat = Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat;

            if (isKitKat && DocumentsContract.IsDocumentUri(context, uri))
            {
                // ExternalStorageProvider
                if (IsExternalStorageDocument(uri))
                {
                    string docId = DocumentsContract.GetDocumentId(uri);

                    char[]   chars = { ':' };
                    string[] split = docId.Split(chars);
                    string   type  = split[0];

                    if ("primary".Equals(type, StringComparison.OrdinalIgnoreCase))
                    {
                        return(global::Android.OS.Environment.ExternalStorageDirectory + "/" + split[1]);
                    }
                }
                // Google Drive
                else if (IsDiskContentUri(uri))
                {
                    return(GetDriveFileAbsolutePath(context, uri));
                }
                // DownloadsProvider
                else if (IsDownloadsDocument(uri))
                {
                    try
                    {
                        string id = DocumentsContract.GetDocumentId(uri);

                        if (!TextUtils.IsEmpty(id))
                        {
                            if (id.StartsWith("raw:"))
                            {
                                return(id.Replace("raw:", ""));
                            }

                            string[] contentUriPrefixesToTry = new string[] {
                                "content://downloads/public_downloads",
                                "content://downloads/my_downloads",
                                "content://downloads/all_downloads"
                            };

                            string path = null;

                            foreach (string contentUriPrefix in contentUriPrefixesToTry)
                            {
                                global::Android.Net.Uri contentUri = ContentUris.WithAppendedId(
                                    global::Android.Net.Uri.Parse(contentUriPrefix), long.Parse(id));

                                path = GetDataColumn(context, contentUri, null, null);

                                if (!string.IsNullOrEmpty(path))
                                {
                                    return(path);
                                }
                            }

                            // path could not be retrieved using ContentResolver, therefore copy file to accessible cache using streams
                            string       fileName = GetFileName(context, uri);
                            Java.IO.File cacheDir = GetDocumentCacheDir(context);
                            Java.IO.File file     = GenerateFileName(fileName, cacheDir);

                            if (file != null)
                            {
                                path = file.AbsolutePath;
                                SaveFileFromUri(context, uri, path);
                                //CopyFileAsync(context, uri, path);
                            }

                            // last try
                            if (string.IsNullOrEmpty(path))
                            {
                                return(global::Android.OS.Environment.ExternalStorageDirectory.ToString() + "/Download/" + GetFileName(context, uri));
                            }

                            return(path);
                        }
                    }
                    catch
                    {
                        return(global::Android.OS.Environment.ExternalStorageDirectory.ToString() + "/Download/" + GetFileName(context, uri));
                    }
                }
                // MediaProvider
                else if (IsMediaDocument(uri))
                {
                    string docId = DocumentsContract.GetDocumentId(uri);

                    char[]   chars = { ':' };
                    string[] split = docId.Split(chars);

                    string type = split[0];

                    global::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;
                    }

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

                    return(GetDataColumn(context, contentUri, selection, selectionArgs));
                }
            }
            // MediaStore (and general)
            else if ("content".Equals(uri.Scheme, StringComparison.OrdinalIgnoreCase))
            {
                // Return the remote address
                if (IsGooglePhotosUri(uri))
                {
                    return(uri.LastPathSegment);
                }

                // Google Disk document .legacy
                if (IsDiskLegacyContentUri(uri))
                {
                    return(GetDriveFileAbsolutePath(context, uri));
                }
                return(GetDataColumn(context, uri, null, null));
            }
            // File
            else if ("file".Equals(uri.Scheme, StringComparison.OrdinalIgnoreCase))
            {
                return(uri.Path);
            }

            return(null);
        }
Пример #19
0
        public static string GetPathToImage(Activity activity, Android.Net.Uri uri)
        {
            Boolean isKitKat = Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat;

            if (isKitKat && DocumentsContract.IsDocumentUri(activity, uri))
            {
                if (isExternalStorageDocument(uri))
                {
                    string   docID = DocumentsContract.GetDocumentId(uri);
                    string[] split = docID.Split(':');
                    string   type  = split[0];

                    if (type.Equals("primary", StringComparison.OrdinalIgnoreCase))
                    {
                        return((string)Android.OS.Environment.ExternalStorageDirectory + "/" + split[1]);
                    }
                }
                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(activity, contentUri, null, null));
                }
                else if (isMediaDocument(uri))
                {
                    string   docId = DocumentsContract.GetDocumentId(uri);
                    string[] split = docId.Split(':');
                    string   type  = split[0];

                    Android.Net.Uri contentUri = null;

                    switch (type.ToLower())
                    {
                    case "image":
                        contentUri = MediaStore.Images.Media.ExternalContentUri;
                        break;

                    case "video":
                        contentUri = MediaStore.Video.Media.ExternalContentUri;
                        break;

                    case "audio":
                        contentUri = MediaStore.Audio.Media.ExternalContentUri;
                        break;
                    }

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

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

            return(null);
        }
Пример #20
0
        private void SetNotifySoundPathWithUri(Android.Net.Uri uri)
        {
            bool isKitKat = Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat;

            if (isKitKat && DocumentsContract.IsDocumentUri(this, uri))
            {
                // ExternalStorageProvider
                if (isExternalStorageDocument(uri))
                {
                    string docId = DocumentsContract.GetDocumentId(uri);

                    char[]   chars = { ':' };
                    string[] split = docId.Split(chars);
                    string   type  = split[0];

                    if ("primary".Equals(type, StringComparison.OrdinalIgnoreCase))
                    {
                        streamerData.NotifySoundPath = Android.OS.Environment.ExternalStorageDirectory + "/" + split[1];
                        return;
                    }
                }
                // DownloadsProvider
                else if (isDownloadsDocument(uri))
                {
                    var id = DocumentsContract.GetDocumentId(uri);

                    if (id != null && id.StartsWith("raw:"))
                    {
                        streamerData.NotifySoundPath = id.Substring(4);
                        return;
                    }

                    String[] contentUriPrefixesToTry = new String[] {
                        "content://downloads/public_downloads",
                        "content://downloads/my_downloads",
                        "content://downloads/all_downloads"
                    };

                    foreach (String contentUriPrefix in contentUriPrefixesToTry)
                    {
                        Uri contentUri = ContentUris.WithAppendedId(Uri.Parse(contentUriPrefix), long.Parse(id));
                        try
                        {
                            String path = getDataColumn(this, contentUri, null, null);
                            if (path != null)
                            {
                                streamerData.NotifySoundPath = path;
                                return;
                            }
                        }
                        catch (Exception e) { }
                    }

                    var builder = new AlertDialog.Builder(this);
                    builder.SetTitle(Resource.String.app_name);
                    builder.SetMessage(Resource.String.need_to_copy_to_local);
                    builder.SetPositiveButton(Resource.String.yes, (ev, ct) =>
                    {
                        try
                        {
                            Stream stream = ContentResolver.OpenInputStream(uri);
                            var data      = AndroidPlatformUtils.ReadFully(stream);
                            stream.Close();
                            var notify = Path.Combine(PlatformUtils.Instance.GetConfigBasePath(), "notify");
                            PlatformUtils.Instance.EnsureDirectory(notify);
                            streamerData.NotifySoundPath = Path.Combine(notify, streamerData.Id);
                            PlatformUtils.Instance.WriteAllBytes(streamerData.NotifySoundPath, data);
                        }
                        catch
                        {
                            streamerData.NotifySoundPath = null;
                        }
                    });
                    builder.SetNegativeButton(Resource.String.no, (ev, ct) =>
                    {
                    });
                    builder.Show();
                    return;
                }
                // MediaProvider
                else if (isMediaDocument(uri))
                {
                    String docId = DocumentsContract.GetDocumentId(uri);

                    char[]   chars = { ':' };
                    String[] split = docId.Split(chars);

                    String 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;
                    }

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

                    streamerData.NotifySoundPath = getDataColumn(this, contentUri, selection, selectionArgs);
                    return;
                }
            }
            // MediaStore (and general)
            else if ("content".Equals(uri.Scheme, StringComparison.OrdinalIgnoreCase))
            {
                // Return the remote address
                if (isGooglePhotosUri(uri))
                {
                    streamerData.NotifySoundPath = uri.LastPathSegment;
                    return;
                }
                streamerData.NotifySoundPath = getDataColumn(this, uri, null, null);
                return;
            }
            // File
            else if ("file".Equals(uri.Scheme, StringComparison.OrdinalIgnoreCase))
            {
                streamerData.NotifySoundPath = uri.Path;
                return;
            }
        }
Пример #21
0
        public static string GetFilePath(this Uri uri, Context context)
        {
            try
            {
                var isKitKat = Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat;

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

                        return(Environment.GetExternalStoragePublicDirectory(type) + "/" + split[1]);
                    }
                    // DownloadsProvider
                    if (IsDownloadsDocument(uri))
                    {
                        var id         = DocumentsContract.GetDocumentId(uri);
                        var contentUri = ContentUris.WithAppendedId(
                            Uri.Parse("content://downloads/public_downloads"), Long.ParseLong(id));

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

                        Uri contentUri = null;
                        switch (type)
                        {
                        case "image":
                            contentUri = MediaStore.Images.Media.ExternalContentUri;
                            break;

                        case "video":
                            contentUri = MediaStore.Video.Media.ExternalContentUri;
                            break;

                        case "audio":
                            contentUri = MediaStore.Audio.Media.ExternalContentUri;
                            break;
                        }

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

                        return(GetDataColumn(context, contentUri, selection, selectionArgs));
                    }
                }
                // MediaStore (and general)
                else
                {
                    switch (uri.Scheme)
                    {
                    case "content":
                        return(GetDataColumn(context, uri, null, null));

                    case "file":
                        return(uri.Path);
                    }
                }

                return(null);
            }
            catch (Exception e)
            {
                Debug.WriteLine($"[Uri.GetPath Extension error]\n{e.Message}\n{e.StackTrace}");
                return(null);
            }
        }
Пример #22
0
        /**
         * Get a file path from a Uri. This will get the the path for Storage Access
         * Framework Documents, as well as the _data field for the MediaStore and
         * other file-based ContentProviders.
         *
         * @param context The context.
         * @param uri     The Uri to query.
         * @author paulburke
         */
        // @SuppressLint("NewApi")
        public static string GetRealPathFromURI_API19(Context context, Uri uri)
        {
            bool isKitKat = Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat;

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

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

                    // TODO handle non-primary volumes
                }
                // DownloadsProvider
                else if (isDownloadsDocument(uri))
                {
                    string id = DocumentsContract.GetDocumentId(uri);
                    Uri    contentUri;
                    try
                    {
                        long iid = long.Parse(id);
                        contentUri = ContentUris.WithAppendedId(
                            Uri.Parse("content://downloads/public_downloads"), iid);
                    }
                    catch
                    {
                        return(id);
                    }

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

                    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;
                    }

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

                    return(getDataColumn(context, contentUri, selection, selectionArgs));
                }
            }
            // MediaStore (and general)
            else if ("content".Equals(uri.Scheme, StringComparison.InvariantCultureIgnoreCase))
            {
                // Return the remote address
                if (isGooglePhotosUri(uri))
                {
                    return(uri.LastPathSegment);
                }

                return(getDataColumn(context, uri, null, null));
            }
            // File
            else if ("file".Equals(uri.Scheme, StringComparison.InvariantCultureIgnoreCase))
            {
                return(uri.Path);
            }

            return(null);
        }
Пример #23
0
        public static string GetUriRealPath(Context context, Uri uri)
        {
            if (uri == null)
            {
                return(null);
            }

            string ret = "";

            if (context != null)
            {
                if ("content".Equals(uri.Scheme, StringComparison.OrdinalIgnoreCase))
                {
                    ret = "com.google.android.apps.photos.content".Equals(uri.Authority) ? uri.LastPathSegment : GetRealPathFromMediaStore(context, uri, null);
                }
                else if ("file".Equals(uri.Scheme, StringComparison.OrdinalIgnoreCase))
                {
                    ret = uri.Path;
                }
                else if (DocumentsContract.IsDocumentUri(context, uri)) // Document uri
                {
                    var documentId   = DocumentsContract.GetDocumentId(uri);
                    var uriAuthority = uri.Authority;

                    if ("com.android.providers.media.documents".Equals(uriAuthority))
                    {
                        string[] idArr = documentId.Split(':');
                        if (idArr.Length == 2)
                        {
                            var docType   = idArr[0];
                            var realDocId = idArr[1];

                            var mediaContentUri = MediaStore.Images.Media.ExternalContentUri;

                            switch (docType)
                            {
                            case "image":
                                mediaContentUri = MediaStore.Images.Media.ExternalContentUri;
                                break;

                            case "video":
                                mediaContentUri = MediaStore.Video.Media.ExternalContentUri;
                                break;

                            case "audio":
                                mediaContentUri = MediaStore.Audio.Media.ExternalContentUri;
                                break;
                            }

                            var whereClause = MediaStore.Images.ImageColumns.Id + " = " + realDocId;

                            ret = GetRealPathFromMediaStore(context, mediaContentUri, whereClause);
                        }
                    }
                    else if ("com.android.providers.downloads.documents".Equals(uriAuthority))
                    {
                        var downloadUri         = Uri.Parse("content://downloads/public_downloads");
                        var downloadUriAppendId = ContentUris.WithAppendedId(downloadUri, long.Parse(documentId));

                        ret = GetRealPathFromMediaStore(context, downloadUriAppendId, null);
                    }
                    else if ("com.android.externalstorage.documents".Equals(uriAuthority))
                    {
                        string[] idArr = documentId.Split(':');
                        if (idArr.Length == 2)
                        {
                            var type      = idArr[0];
                            var realDocId = idArr[1];

                            if ("primary".Equals(type, StringComparison.OrdinalIgnoreCase))
                            {
                                ret = Environment.ExternalStorageDirectory + "/" + realDocId;
                            }
                        }
                    }
                }
            }

            return(ret);
        }
Пример #24
0
        public static string GetMediaPath(Context context, Uri uri)
        {
            bool afterKitKat = Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat;

            if (afterKitKat && DocumentsContract.IsDocumentUri(context, uri))                       //   DocumentProvider
            {
                string docId = DocumentsContract.GetDocumentId(uri);

                if (IsExternalStorageDocument(uri))         //  ExternalStorageProvider
                {
                    string[] split = docId.Split(':');
                    string   type  = split[0];

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

                    // TODO handle non-primary volumes
                }
                else if (IsDownloadsDocument(uri))          //  DownloadsProvider
                {
                    long id;
                    if (!long.TryParse(docId, out id))
                    {
                        return(null);
                    }

                    Uri contentUri = ContentUris.WithAppendedId(Uri.Parse("content://downloads/public_downloads"), id);

                    return(GetDataColumn(context, contentUri, null, null));
                }
                else if (IsMediaDocument(uri))              //  MediaProvider
                {
                    string[] split = docId.Split(':');
                    string   type  = split[0];

                    Uri contentUri = null;

                    if (string.Equals(type, "image", StringComparison.OrdinalIgnoreCase))
                    {
                        contentUri = MediaStore.Images.Media.ExternalContentUri;
                    }
                    else if (string.Equals(type, "video", StringComparison.OrdinalIgnoreCase))
                    {
                        contentUri = MediaStore.Video.Media.ExternalContentUri;
                    }
                    else if (string.Equals(type, "audio", StringComparison.OrdinalIgnoreCase))
                    {
                        contentUri = MediaStore.Audio.Media.ExternalContentUri;
                    }

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

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

            return(null);
        }
Пример #25
0
        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)
            if (isMediaStore(uri.Scheme))
            {
                return(getDataColumn(context, uri, null, null));
            }
            // File
            else if ("file".Equals(uri.Scheme, StringComparison.OrdinalIgnoreCase))
            {
                return(uri.Path);
            }

            return(null);
        }
Пример #26
0
        public string GetLocalDownloadPath(string uriString)
        {
            bool isKitKat = Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat;

            Android.Net.Uri uri = Android.Net.Uri.Parse(uriString);
            //Uri uri = data.Data;
            string path = "";


            if (!isKitKat)
            {
                //the usual function
                //path = GetPathToImage(uri);
            }
            else
            {
                //Android.App.Application.Contex
                //bool isdoc = DocumentsContract.IsDocumentUri(this, uri);
                bool isdoc = DocumentsContract.IsDocumentUri(Android.App.Application.Context, uri);
                if (isdoc)
                {
                    if (IsGoogleDrive(uri))
                    {
                        CopyFile(Android.App.Application.Context, uri);
                        return(uri.Path);
                    }

                    if (IsExternalStorageDocument(uri))
                    {
                        CopyFile(Android.App.Application.Context, uri);
                        ////Actually Here i don t know how to handle all possibility.......
                        //string docId = DocumentsContract.GetDocumentId(uri);
                        //string[] split = docId.Split(':');
                        //string type = split[0];

                        //if ("primary".Equals(type))
                        //{
                        //    //return Android.OS.Environment.GetExternalStoragePublicDirectory() + "/" + split[1];
                        //    return Environment.GetExternalStoragePublicDirectory().ToString()
                        //        + "/"
                        //        + split[1];
                        //}


                        return(uri.Path);
                    }
                    else if (IsDownloadsDocument(uri))
                    {
                        CopyFile(Android.App.Application.Context, uri);
                        string id = DocumentsContract.GetDocumentId(uri);

                        ////content://com.android.providers.downloads.documents/document/21
                        ////Uri contentUri = ContentUris.WithAppendedId(Uri.Parse("content://downloads/public_downloads"), System.Convert.ToInt64(id));
                        //Uri contentUri = ContentUris.WithAppendedId(Uri.Parse("content://downloads/my_downloads"), System.Convert.ToInt64(id));
                        ////Uri contentUri = ContentUris.WithAppendedId(Uri.Parse("content://com.android.providers.downloads.documents/document"), System.Convert.ToInt64(id));

                        //path = GetDataColumn(Android.App.Application.Context, contentUri, null, null);

                        string[] contentUriPrefixesToTry = new string[]
                        {
                            "content://downloads/public_downloads",
                            "content://downloads/my_downloads"
                        };

                        foreach (string contentUriPrefix in contentUriPrefixesToTry)
                        {
                            Android.Net.Uri contentUri = ContentUris.WithAppendedId(
                                Android.Net.Uri.Parse(contentUriPrefix), long.Parse(id));

                            try
                            {
                                path = GetDataColumn(Android.App.Application.Context, contentUri, null, null);
                                if (path != null)
                                {
                                    return(path);
                                }
                            }
                            catch (System.Exception ex)
                            {
                                System.Diagnostics.Debug.WriteLine("Image Exception : " + ex.Message);
                                // ignore exception; path can't be retrieved using ContentResolver
                            }
                        }
                    }
                    else if (IsMediaDocument(uri))
                    {
                        string   docId = DocumentsContract.GetDocumentId(uri);
                        string[] split = docId.Split(':');

                        string type = split[0];

                        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;
                        }

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

                        path = GetDataColumn(Android.App.Application.Context, contentUri, selection, selectionArgs);
                    }
                }
            }
            return(path);
        }
Пример #27
0
        /// <summary>
        /// Method to return File path of a Gallery Image from URI.
        /// </summary>
        /// <param name="context">The Context.</param>
        /// <param name="uri">URI to Convert from.</param>
        /// <returns>The Full File Path.</returns>
        public static string GetPathFromUri(Context context, DroidUri uri)
        {
            //check here to KITKAT or new version
            // bool isKitKat = Build.VERSION.SdkInt >= Build.VERSION_CODES.Kitkat;
            bool isKitKat = Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat;

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

                    if (type.Equals("primary", System.StringComparison.InvariantCultureIgnoreCase))
                    {
                        return(DroidEnv.ExternalStorageDirectory + "/" + split[1]);
                    }
                }
                // DownloadsProvider
                else if (isDownloadsDocument(uri))
                {
                    string   id         = DocumentsContract.GetDocumentId(uri);
                    DroidUri ContentUri = ContentUris.WithAppendedId(
                        DroidUri.Parse("content://downloads/public_downloads"), long.Parse(id));

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

                    DroidUri 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;
                    }

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

                    return(GetDataColumn(context, contentUri, selection, selectionArgs));
                }
            }
            // MediaStore (and general)
            else if (uri.Scheme.Equals("content", System.StringComparison.InvariantCultureIgnoreCase))
            {
                // Return the remote address
                if (isGooglePhotosUri(uri))
                {
                    return(uri.LastPathSegment);
                }

                return(GetDataColumn(context, uri, null, null));
            }
            // File
            else if (uri.Scheme.Equals("file", System.StringComparison.InvariantCultureIgnoreCase))
            {
                return(uri.Path);
            }

            return(null);
        }
        /**
         * Get the file path for a uri. This is a convoluted way to get the path for an Uri created using the
         * StorageAccessFramework. This in no way is the official way to do this but there does not seem to be a better
         * way to do this at this point. It is taken from https://github.com/iPaulPro/aFileChooser.
         *
         * @param context The context of the application
         * @param uri The uri of the saved file
         * @return The file with path pointing to the saved file. It can return null if we can't resolve the uri properly.
         */
        public static string GetFileForUri(Context context, string filePath)
        {
            var uri   = Android.Net.Uri.Parse(filePath);
            var csuri = new Uri(uri.ToString());

            String path = null;

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

                    if ("primary".Equals(type, StringComparison.OrdinalIgnoreCase))
                    {
                        path = Android.OS.Environment.ExternalStorageState + "/" + split[1];
                    }
                }
                else if (IsDownloadsDocument(csuri))
                {
                    // DownloadsProvider
                    var id         = DocumentsContract.GetDocumentId(uri);
                    var contentUri = ContentUris
                                     .WithAppendedId(
                        Android.Net.Uri.Parse("content://downloads/public_downloads"),
                        long.Parse(id));

                    path = GetDataColumn(context, contentUri, null, null);
                }
                else if (IsMediaDocument(csuri))
                {
                    // MediaProvider
                    var docId = DocumentsContract.GetDocumentId(uri);
                    var 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[] {
                        split[1]
                    };

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

            return(path);
        }
Пример #29
0
        /**
         * Get a file path from a Uri. This will get the the path for Storage Access
         * Framework Documents, as well as the _data field for the MediaStore and
         * other file-based ContentProviders.<br>
         * <br>
         * Callers should check whether the path is local before assuming it
         * represents a local file.
         *
         * @param context The context.
         * @param uri The Uri to query.
         * @see #isLocal(string)
         * @see #getFile(Context, Uri)
         * @author paulburke
         */
        public static string GetPath(Context context, Uri uri)
        {
#if DEBUG
            Log.Debug("FilePathHelper -",
                      "Authority: " + uri.Authority +
                      ", Fragment: " + uri.Fragment +
                      ", Port: " + uri.Port +
                      ", Query: " + uri.Query +
                      ", Scheme: " + uri.Scheme +
                      ", Host: " + uri.Host +
                      ", Segments: " + uri.PathSegments.ToString()
                      );
#endif

            // DocumentProvider
            if (DocumentsContract.IsDocumentUri(context, uri))
            {
                // LocalStorageProvider
                if (IsLocalStorageDocument(uri))
                {
                    // The path is the id
                    return(DocumentsContract.GetDocumentId(uri));
                }
                // ExternalStorageProvider
                else if (IsExternalStorageDocument(uri))
                {
                    string   docId = DocumentsContract.GetDocumentId(uri);
                    string[] split = docId.Split(':');
                    string   type  = split[0];

                    if ("primary".ToLower() == type.ToLower())
                    {
                        return(Android.OS.Environment.ExternalStorageDirectory + "/" + split[1]);
                    }

                    // TODO handle non-primary volumes
                }
                // DownloadsProvider
                else if (IsDownloadsDocument(uri))
                {
                    string id         = DocumentsContract.GetDocumentId(uri);
                    Uri    contentUri = ContentUris.WithAppendedId(Uri.Parse("content://downloads/public_downloads"), long.Parse(id));

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

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

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

                    return(GetDataColumn(context, contentUri, selection, selectionArgs));
                }
            }
            // MediaStore (and general)
            else if ("content".ToLower() == uri.Scheme.ToLower())
            {
                // Return the remote address
                if (IsGooglePhotosUri(uri))
                {
                    return(uri.LastPathSegment);
                }

                return(GetDataColumn(context, uri, null, null));
            }
            // File
            else if ("file".ToLower() == uri.Scheme.ToLower())
            {
                return(uri.Path);
            }

            return(null);
        }
Пример #30
0
 private static bool IsDocumentUri(Context context, Uri uri) => DocumentsContract.IsDocumentUri(context, uri);