问题描述
我正在尝试通过 openFileDialog 从用户那里获取图像,然后通过用户选择的新图像更改现有图像,然后将该新图像保存到应用程序中具有完全相同文件名的文件夹中。 第一次添加图像没问题,但是如果用户想要更改图像,则尝试替换图像很麻烦。每当我尝试这个时,我都会收到错误:
System.IO.IOException: '该进程无法访问文件 'File Path',因为它正被另一个进程使用。'
我知道我的应用程序正在使用该文件来显示图像,但是我可以以某种方式结束此过程,然后使用相同的文件名保存新图像吗? 我尝试使用 File.Delete(filename),但它给了我同样的错误。
WPF 应用程序的屏幕截图: screenshot
private BitmapImage _previewImage;
public BitmapImage PreviewImage
{
get { return _previewImage; }
set { _previewImage = value;
NotifyPropertyChanged();
}
}
public void AddImage()
{
OpenFileDialog openFileDialog = new OpenFileDialog()
{
InitialDirectory = Environment.SpecialFolder.MyPictures.ToString(),Filter = "Image Files |*.png;*.jpeg;*.jpg;*.gif",FilterIndex = 0,};
if (openFileDialog.ShowDialog() == true)
{
string uriString = openFileDialog.FileName;
PreviewImage = new BitmapImage(new Uri(uriString,UriKind.Absolute));
}
}
现在,当我想执行以下代码时,它会在我启动文件流的行上抛出错误, 再次,只有当我已经保存了图像时,我只想用新图像替换图像但保持相同的文件名。 对于初始保存,这可以正常工作:
public string SaveImage()
{
if (PreviewImage != null)
{
string extension = Path.GetExtension(PreviewImage.UriSource.ToString());
string filename = @"\" + Exhibition.Title + extension;
string fullpath = Dir + filename;
using (FileStream filestream = new FileStream(fullpath,FileMode.Create,FileAccess.Write))
{
BitmapEncoder encoder;
switch (extension)
{
case ".gif": encoder = new GifBitmapEncoder(); break;
case ".png": encoder = new PngBitmapEncoder(); break;
default: encoder = new JpegBitmapEncoder(); break;
}
encoder.Frames.Add(BitmapFrame.Create(PreviewImage));
encoder.Save(filestream);
}
return filename;
}
return null;
}
这可能是相关的,因为我觉得这可能是问题所在?每当我想编辑我的展览时,我都会在我的构造函数中使用此目录设置我的图像,如下所示:
string Dir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\..\..\Images";
public NewExhibitionviewmodel(int? exhbitionId)
{
if (exhbitionId != null)
{
Exhibition = unitOfWork.ExhibitionRepo.Get(
x => x.ExhibitionID == exhbitionId,x => x.ExhibitionArtists.Select(y => y.Artist)
).SingleOrDefault();
//Exhibition.ImageFile = "\ExhibtionName.jpg"
PreviewImage = new BitmapImage(new Uri(Dir + Exhibition.ImageFile));
...
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)