user875234
user875234

Reputation: 2517

Is it okay to write a file directly to Android.OS.Environment.ExternalStorageDirectory?

I've been trying to port some older code and came to a method that writes a stream to a file before sending it as an attachment in an email.

That code ultimately uses

var path = MediaStore.Images.Media.InsertImage(Forms.Context.ContentResolver, myBitmap, "My Bitmap", "MyBitmap.png");

to save the file. path ends up being content://media/external/images/media/164 where 164 appears to just be the nth thing saved.

Originally that code didn't work (just because of permissions, at it turned out) so I tried replacing it with some normal C#:

string dir = Android.OS.Environment.ExternalStorageDirectory.ToString();
string filePath = System.IO.Path.Combine(dir, fileName);
using (System.IO.Stream file = System.IO.File.Create(filePath))
{
    myStream.CopyTo(file);
}

and it wrote the file fine. That path looks like /storage/emulated/0/MyBitmap.png.


Now the strange thing is I can't attach the second path (/storage/emulated/0/MyBitmap.png) to the email even though the file exists, is not empty, the code has read access, and the user has given permission. But the first path (content://media/external/images/media/164) works no problem, even though I would not expect it to:

enter image description here

Can you tell me what's going on here? I've googled this and thought I was doing it in a way that would work. But for it to not only not work but to have a different way of doing it, that makes no sense, work is really confusing.

Upvotes: 0

Views: 42

Answers (1)

Marcos Vasconcelos
Marcos Vasconcelos

Reputation: 18276

content:// uris are resolved by applications to give a InputStream for someone who try to "resolve" it, you can implements ContentProvider and handle your internal paths and just give the URI. OR try to give the schema to the path as file://storage/emu...

Upvotes: 1

Related Questions