问题描述
我在我的wpf应用程序中使用以下代码显示一些图像:
I am displaying some image in my wpf app using following code:
<Image Source="{Binding Path=TemplateImagePath, Mode=TwoWay}" Grid.Row="3" Grid.Column="2" Width="400" Height="200"/>
并在代码后面的构造函数中设置绑定属性,下面是代码: / p>
and setting it's binding property inside code behind's constructor by navigating through some directory, below is the code:
DirectoryInfo Dir = new DirectoryInfo(@"D:/Template");
if (Dir.Exists)
{
if (Dir.GetFiles().Count() > 0)
{
foreach (FileInfo item in Dir.GetFiles())
{
TemplateImagePath = item.FullName;
}
}
}
image我需要删除这个旧的图像,这是我在做以下方式和设置图像绑定为null:
but if user upload some other image then I need to delete this old image which is I am doing in the following way and setting image binding to null:
DirectoryInfo Dir = new DirectoryInfo(@"D:/Template");
if (Dir.Exists)
{
if (Dir.GetFiles().Count() > 0)
{
foreach (FileInfo item in Dir.GetFiles())
{
TemplateImagePath= null;
File.Delete(item.FullName);
}
}
}
删除其他进程使用的文件。
如何删除它?
But Iam getting exception that Cannot delete file used by some other process.How can I delete it?
推荐答案
为了能够删除图像, ImageControl,您必须创建新的或对象,其具有设置。
In order to be able to delete the image while it is displayed in an ImageControl, you have to create a new BitmapImage or BitmapFrame object that has BitmapCacheOption.OnLoad set. The bitmap will then be loaded from file immediately and the file is not locked afterwards.
更改属性 string TemplateImagePath
到 ImageSource TemplateImage
并以如下方式进行绑定:
Change your property from string TemplateImagePath
to ImageSource TemplateImage
and bind like this:
<Image Source="{Binding TemplateImage}"/>
设置 TemplateImage
BitmapImage image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = new Uri(item.FullName);
image.EndInit();
TemplateImage = image;
或:
TemplateImage = BitmapFrame.Create(
new Uri(item.FullName),
BitmapCreateOptions.None,
BitmapCacheOption.OnLoad);
如果您要保持绑定到 TemplateImagePath
属性,您可以改为使用,将字符串转换为ImageSource如上所示。
If you want to keep binding to your TemplateImagePath
property you may instead use a binding converter that converts the string to an ImageSource as shown above.
这篇关于无法删除某些其他进程使用的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!