We are working on an application that receives huge amounts of data from the backend. This also contains a list of images, and the format of the image response is always base64 string images. This cannot be changed.
In the first version, we converted it to a byte array, and the ImageSource converted it to an image, but this has really bad performance, and the application will be very slow if multiple images are added.
so we decided to save the images locally on the device in a background job and if this local path is available, the ImageSource will use the path, fallback is the byte ImageSource.
the question is if this is a good solution to save the files locally:
private async Task LoadImagesToLocalStorage(Guid activityId, Attachment attachment)
{
var name = attachment.Name;
var splits = attachment.Name.Split("Library/");
if (splits.Length > 1)
{
name = splits[1];
}
if (!string.IsNullOrWhiteSpace(name) && File.Exists(name))
{
return;
}
// Ensure the directory exists
var cacheDir = FileSystem.Current.AppDataDirectory;
var localFilePath = Path.Combine(cacheDir, name);
if (File.Exists(localFilePath))
{
attachment.LocalPath = localFilePath;
}
else
{
try
{
// create stream from byte array
using MemoryStream sourceStream = new MemoryStream(attachment.Data);
await using FileStream localFileStream = File.Open(localFilePath, FileMode.OpenOrCreate);
await sourceStream.CopyToAsync(localFileStream);
attachment.LocalPath = localFilePath;
}
catch (Exception e)
{
_logger.LogError(e, e.Message);
return;
}
}
await _attachmentDatabase.SaveAttachment(activityId, attachment, CancellationToken.None)
.ConfigureAwait(false);
}
2