A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
Hello,
string localFilePath = Path.Combine(FileSystem.CacheDirectory, photo.FileName);
The API path provided by FileSystem is a private path for the program. Its advantage is that files can be saved without permission, but its disadvantage is that it is not easy for users to find them.
For your expected behavior, you can refer to the following code to save the file to Pictures/AppName folder on Windows and save the picture to the photo album in Android.
For Windows:
async Task TakePhoto()
{
var photo = await MediaPicker.Default.CapturePhotoAsync();
if (photo != null)
{
// Getting the file result information
using Stream sourceStream = await photo.OpenReadAsync();
#if WINDOWS
string localDirectoryPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), AppInfo.Name);
Console.WriteLine(localDirectoryPath);
if (!Directory.Exists(localDirectoryPath))
{
Directory.CreateDirectory(localDirectoryPath);
}
string localFilePath = Path.Combine(localDirectoryPath, photo.FileName);
#elif ANDROID
#endif
}
}
For Andorid:
Step 1. Add the following code into MainActivity.cs:
public static MainActivity Instance { get; private set; }
// Then, make the assignment in the OnCreate method.
Instance = this;
Step 2. Create SavePictureService.cs in Platforms/Android folder, and add the following code:
public static class SavePictureService
{
public static bool SavePicture(byte[] arr, string imageName)
{
var contentValues = new ContentValues();
contentValues.Put(MediaStore.IMediaColumns.DisplayName, imageName);
contentValues.Put(MediaStore.Files.IFileColumns.MimeType, "image/png");
contentValues.Put(MediaStore.IMediaColumns.RelativePath, "Pictures/relativePath");
try
{
var uri = MainActivity.Instance.ContentResolver.Insert(MediaStore.Images.Media.ExternalContentUri, contentValues);
var output = MainActivity.Instance.ContentResolver.OpenOutputStream(uri);
output.Write(arr, 0, arr.Length);
output.Flush();
output.Close();
}
catch (System.Exception ex)
{
Console.Write(ex.ToString());
return false;
}
contentValues.Put(MediaStore.IMediaColumns.IsPending, 1);
return true;
}
}
Step 3. Save photo into Android album.
#elif ANDROID
// convert stream to byte[]
MemoryStream ms = new MemoryStream();
sourceStream.CopyTo(ms);
var b = ms.ToArray();
// save photo into android album.
MauiApp22.Platforms.Android.SavePictureService.SavePicture(b, photo.FileName);
#endif
Best Regards,
Alec Liu.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.