Forum Xamarin.Android

Retrieving a seekable Stream from StorageAccessFramework: what's the best way?

My application uses StorageAccessFramework (SAF) to manage files. When I select a file through SAF, I get a URI (Android.Net.uri) labeled "inFileName" that I can convert to a Stream through something like the following:
Stream InStream = ContentResolver.OpenInputStream(inFileName)
"InStream" isn't seekable so some action that I need to take on it (like reading bytes at a given offset) couldn't be done directly. The best workaround I thought about is to copy "InStream" to a FileStream based off a temporary file. FileStream is perfectly seekable and it could be enough for me. Anyway this solution is quite an overkill because I'm duplicating a file that's already in the device storage: this may also lead to lack of space if I open a very large file and for the same reason I can't copy InStream to a MemoryStream.

I've also thought about a different workaround that uses "ParcelFileDescriptor" in order to gain access :
ParcelFileDescriptor fdi = ContentResolver.OpenFileDescriptor(inFileName, "rw"); IntPtr fHandle = fdi.Handle; FileStream iStream = new FileStream(fdi.Handle, FileAccess.ReadWrite);

Unfortunately, this code raises an exception:
System.IO.IOException: Invalid handle to path "[Unknown]"
... and I acknowledge that I'm surely missing something.

So, the question is: how could I get a seekable stream from an URI in an efficient way?

Thank you :)

Sign In or Register to comment.