Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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).

size1size2

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.

like image 443
nkreipke Avatar asked Dec 26 '22 13:12

nkreipke


1 Answers

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;
like image 69
nkreipke Avatar answered Jan 15 '23 12:01

nkreipke