Download BitmapSource and save it using the same name in WPF & # 8594; IOException

When I try to save a BitmapSource that was downloaded earlier, a message appears System.IO.IOExceptionsaying that another process is accessing this file and the file stream does not open.

If I save only the download earlier, everything works fine.

Download Code:

BitmapImage image = new BitmapImage();

image.BeginInit();
image.UriSource = uri;

if (decodePixelWidth > 0)
image.DecodePixelWidth = decodePixelWidth;

image.EndInit();

save code:

using (FileStream fileStream = new FileStream(Directory + "\\" + FileName + ".jpg", FileMode.Create))
{
    JpegBitmapEncoder encoder = new JpegBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create((BitmapImage)image));
    encoder.QualityLevel = 100;
    encoder.Save(fileStream);
}

It seems that after downloading the image data, the file is still locked, it can never be overwritten while the application that opened it is still running. Any ideas how to solve this? Thanks so much for any solutions.

+5
source share
5 answers

, , , memystream BitmapImage Sreamsource.

:

if (File.Exists(filePath))
{
    MemoryStream memoryStream = new MemoryStream();

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

    image.BeginInit();
    image.StreamSource = memoryStream;

    if (decodePixelWidth > 0)
        image.DecodePixelWidth = decodePixelWidth;

    image.EndInit();
}
+9

, :

var image = new BitmapImage();
image.BeginInit();

// overwrite cache if already exists, to refresh image
image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
// load into memory and unlock file
image.CacheOption = BitmapCacheOption.OnLoad;

image.UriSource = uri;
if (decodePixelWidth > 0) image.DecodePixelWidth = decodePixelWidth;
image.EndInit();
+7

:

image.CacheOption = BitmapCacheOption.OnLoad;

, image.EndInit. BitmapCacheOption.Default , , image.EndInit.

+3

, BitmapImage, GDI +

, .

, bitmapimage.urisource. , , ?

0

CacheOption BitmapCacheOption.OnLoad . , , . , BitmapImage .

0

All Articles