Xamarin.Forms UWP Image never closes opened File

I am displaying a Image in a Xamarin.Forms UWP app, the image resides in the LocalState folder of the app and the image source is set during runtime.

As soon as the image is displayed, the underlying file is opened and can therefore not be renamed in eg the Windows Explorer.

But even when I navigate away from the page displaying the image or set the source of the image to null or a different image, the file is still opened and can't be renamed until I close the UWP app. This behavior doesn't occur on Android or iOS.

How can I release the file displayed by the Image?

XAML Tag for the Image:

<Image x:Name="img"/>

Setting the Image.Source:

string basePath = @"C:UsersssAppDataLocalPackagesf736c883-f105-4d30-a719-4bf328872f5e_nh7s0b45jarrjLocalState";
img.Source = ImageSource.FromFile(Path.Combine(basePath, "beleg.jpg"));

Thank You!

EDIT: This is my working solution, thanks to the help from Clemens!

IFolder localStorage = FileSystem.Current.LocalStorage;
IFile sourceFile = await localStorage.GetFileAsync("beleg.jpg");

var memoryStream = new MemoryStream();
using (var fileStream = await sourceFile.OpenAsync(FileAccess.Read))
{
    await fileStream.CopyToAsync(memoryStream);
}

memoryStream.Position = 0;
img.Source = ImageSource.FromStream(() => memoryStream);

这应该工作(虽然我没有测试过):

var path = Path.Combine(basePath, "beleg.jpg");
var memoryStream = new MemoryStream();

using (var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
    fileStream.CopyTo(memoryStream);
}

memoryStream.Position = 0;
img.Source = ImageSource.FromStream(() => memoryStream);

I've never used Xamarin, but in full-fat .Net, images don't close the file handle until disposed.

Presuming that this is similar, you'd have to load the Image in a 'using' block, but assign to another image via the Clone method. This isn't likely to compile, but you'll get the idea:

using (var loadimage = ImageSource.FromFile(...)) {
    img.Source = loadimage.clone();
}

I presume that this temporarily uses twice as many bytes as those required for a single copy, but at least the file handle closes.

Again - based on knowledge of System.Drawing, rather than anything Xamarin, so take this with a pinch of salt.

链接地址: http://www.djcxy.com/p/40556.html

上一篇: 检查未锁定的文件是否已打开

下一篇: Xamarin.Forms UWP图像从不关闭打开的文件