开发者

WPF: How can I use a picture while I'm showing it?

I'm trying to do so but the program throws this exception:

An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll

Additional information: The process cannot access the file 'C:\Users\Roy\documents\visual studio 2010\Projects\Assignment3\Assignment3\bin\Debug\Images\Chrysanthemum.jpg' because it is being used by another process.

Is there a way to use it while it's open?

code:

if (imgAddMessage.Source != null)
            {开发者_Go百科
                BitmapImage src = (BitmapImage)imgAddMessage.Source;
                if (!Directory.Exists("Images"))
                {
                    Directory.CreateDirectory("Images");
                }

                FileStream stream = new FileStream("Images/" + imageName, FileMode.Create, FileAccess.ReadWrite);
                JpegBitmapEncoder encoder = new JpegBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(src));
                encoder.Save(stream);
                stream.Close();
            }


Two things.

1) Your posted code doesn't have a using statement around the FileStream nor does it call Dispose on it.

2) Whatever piece of code that is showing the picture that you are trying to save, must use FileAccess.Read, because only a single piece of code can hold a write lock on a file. Better yet, if it's your own program that is showing the file, just cache the image into memory and show the image based on the bytes in memory. Then you'll hold no locks on the file and can do whatever you want with it later on...


Just curious if your still having issues.
Did you try the following?

if (imgAddMessage.Source != null)
{
    string imageDirectory = "pack://application:,,,/Images";
    BitmapImage src = (BitmapImage)imgAddMessage.Source;
    if (!Directory.Exists(imageDirectory))
        Directory.CreateDirectory(imageDirectory);

    using (FileStream stream = new FileStream(Path.Combine(imageDirectory, imageName), FileMode.Create, FileAccess.ReadWrite))
    {
        JpegBitmapEncoder encoder = new JpegBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(src));
        encoder.Save(stream);
    }
}

And as @Marco said you must have read/write permission

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜