How to correctly get the file size of an android.net.Uri?
Asked Answered
S

1

6

I have an android.net.Uri pointing to a file of which I need to determine the file size. Currently this is done using a query on contentResolver (I am using Xamarin, so it's C#):

var cursor = contentResolver.Query(uri, new string[] {
    Android.Provider.OpenableColumns.Size,
    Android.Provider.OpenableColumns.DisplayName 
}, null, null, null);
cursor.MoveToFirst();
size = cursor.GetLong(0);
fileName = cursor.GetString(1);
cursor.Close();

This works most of the time, but for some files, the value seems to be slightly bigger than the correct file size (I'm using Total Commander as a reference).

size1 size2

There must be a better way to do this, I really need the exact size information and, as the files are pretty large, can not read them into memory first. And why does my approach produce incorrect results?

Thanks in advance for your help.

Schlessel answered 19/2, 2014 at 13:44 Comment(1)
i have the same issue using the 'recommended' way from developer.android.com/training/secure-file-sharing/… , i am running on emulator api24Equilibrant
S
12

Although I did not find out why the query returns incorrect results, I found another way to get the file size which seems to work:

using (var fd = contentResolver.OpenFileDescriptor(uri, "r"))
    size = fd.StatSize;
Schlessel answered 24/2, 2014 at 10:43 Comment(2)
When you read using the cursor, you are looking at a data stream in memory. That means the size you get is the size of the stream. My best bet is that sometimes you get padding because of how the cursor requests memory (that "nasty" stuff .net managed code makes an effort to hide from us). In your solution, you are using a descriptor that explicitly contains file metadata which gives the correct value and is a correct approach.Armalla
I believe this is not related to .net stuff, I blame google on this. I am facing same issue on native android, check this: #48303472Clemens

© 2022 - 2024 — McMap. All rights reserved.