C# – How to get the file size of android.net.Uri correctly?

How to get the file size of android.net.Uri correctly?… here is a solution to the problem.

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

I

have an android.net.Uri pointing to a file that I need to determine the file size. Currently this is done using a query against contentResolver (I’m 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 in most cases, but for some files the value seems to be slightly larger than the correct file size (I use Total Commander as a reference).

size1 size2

There has to be a better way to do this, I really need exact size information, and since the files are so large, can’t read them into memory first. Why does my method produce incorrect results?

Thanks in advance for your help.

Solution

While I didn’t find the reason why the query returned the wrong result, I found another way to get the file size, which seems to work:

using (var fd = contentResolver.OpenFileDescriptor(uri, "r"))
    size = fd. StatSize;

Related Problems and Solutions