How to dispose bitmapsource

帅比萌擦擦* 提交于 2020-01-03 18:33:36

问题


Am using BitmapSource class for reading an image from my temp folder and then reading the metadata using BitmapMetadata class.

BitmapSource img = BitmapFrame.Create(new Uri(filepath));
 BitmapMetadata meta = (BitmapMetadata)img.Metadata;
DateTime datetaken = DateTime.Parse(meta.DateTaken);
System.IO.File.Delete(filepath);

While i was trying to delete the image am getting an exception saying "The process cannot access the file 'filepath/filename' because it is being used by another process.".I thought of disposing the bitmapsource before deleting the image. While i was searching for the solution i got info like "You do not have to Dispose() a BitmapSource. Unlike some other "image" classes in the Framework, it does not wrap any native resources.

Just let it go out of scope, and the garbage collector will free its memory." in the following link Proper way to dispose a BitmapSource .I just want to delete the file that exists in the physical folder. Is there any proper way for the deletion of physical path. Thanks in advance.


回答1:


You could do as the top suggested answer here and copy the file to a stream first and initialize the bitmap source from the stream e.g.

        MemoryStream memoryStream = new MemoryStream();

        byte[] fileBytes = File.ReadAllBytes(filepath);
        memoryStream.Write(fileBytes, 0, fileBytes.Length);
        memoryStream.Position = 0;

        BitmapSource img = BitmapFrame.Create(memoryStream);
        BitmapMetadata meta = (BitmapMetadata)img.Metadata;
        DateTime datetaken = DateTime.Parse(meta.DateTaken);
        System.IO.File.Delete(filepath);

I've tried this and it works for me



来源:https://stackoverflow.com/questions/18546712/how-to-dispose-bitmapsource

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!