我使用OpenFileDialog
来获取图像的路径,然后将其设置为我的图像源属性imgSelected.Source = new BitmapImage(new Uri(filenameSteg, UriKind.Absolute));
在WPF应用程序中。C#如何处置OpenFileDialog文件
的事情是,我以后需要再次打开该文件,但我无法打开它,因为该文件是正在被其它进程(System.IO.IOException
- >The process cannot access the file
pathToFilebecause it is being used by another process.
)。
需要稍后访问它如下代码:
bitmapSource = JpegBitmapDecoder.Create(File.Open(filenameSteg, FileMode.Open),
BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames[0];
这bitmapSource
是用来给该图像的WriteableBitmap
,并从那里我经历的像素。
有没有办法处理一个文件用OpenFileDialog打开?
我试图转换到IDisposable,使用使用块等,但这个东西是持久的。
编辑:
1 - 我想这(@ctacke答案):
using (var stream = File.Open(filenameSteg, FileMode.Open)){
bitmapSource = JpegBitmapDecoder.Create(stream, BitmapCreateOptions.None,
BitmapCacheOption.OnLoad).Frames[0];}
但它仍然给我约的过程是已经被另一个进程使用的错误,因为即使它会被处置后,我仍然试图打开相同的文件(filenameSteg
),比我在OpenFileDialog
中打开的文件要多。 (或者至少,这就是我看到它。)
2 - 然后我想这(基于@ctacke建议link:
using (FileStream fileStream = new FileStream(filenameSteg+1, FileMode.Create)){
MemoryStream memoryStream = new MemoryStream();
BitmapImage bi = new BitmapImage();
byte[] fileBytes = File.ReadAllBytes(filenameSteg);
memoryStream.Write(fileBytes, 0, fileBytes.Length);
memoryStream.Position = 0;
bi.BeginInit();
bi.StreamSource = memoryStream;
bi.EndInit();
bitmapSource = bi;}
注:请注意,我在这里问filenameSteg +1
那是因为我想测试我的方法的其余部分,所以我创建了一个副本文件,并简单地为其名称添加了一个1,这就是说,当使用filenameSteg
作为真实时,它给了我同样的错误,再次怀疑是我仍然要求打开以前在OpenFileDialog
中打开的相同图像。
3 - 我想到了另一种方法,它不需要我处置打开的图像:
当我打开图像在OpenFileDialog
第一次,我在图像的字节数组存储在一个变量如此我可以使用BitmapFactory
和字节数组创建WriteableBitmap
。
// This is in the OpenFileDialog. It is where I stock the image "pixels" in a byte array.
bytesArrayImage = File.ReadAllBytes(filenameSteg);
//And then later when I needed the WriteableBitmap, I used the byte array and the BitmapFactory
//imgSelected being the Image containing the image I opened in the OpenFileDialog, I used it's
//width and height
wb = BitmapFactory.New(Convert.ToInt32(imgSelected.Width),
Convert.ToInt32(imgSelected.Height)).FromByteArray(bytesArrayImage);
这种方法的问题是,一些图片工作正常,我可以使用的字节数组创建WriteableBitmap
并通过它的像素,但在其他情况下,它给了我一个AccessViolationException
指出:Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
。换句话说,试图绕过处理问题让我陷入另一个问题。
感谢@ctacke的快速回复,我编辑我既你提到我的方法问题(使用using块来获取流,然后将它置于)以及您提供的链接中的信息。在我试图绕过它之后,我也把现在的状态放在了现在。 – Marks