我有一个由我创建的用户控件,其中包含Image,TextBlock和TextBox。我们的想法是编写一个可以读取目录中所有图像文件的应用程序,并为每个文件创建用户控件,并将文件路径作为参数。
namespace ImageViewerMother
{
/// <summary>
/// Interaction logic for ImageRep.xaml
/// </summary>
public partial class ImageRep : UserControl
{
public string path { get; set; }
public string name { get; set; }
public ImageRep(string path)
{
this.path = path;
InitializeComponent();
InitializeImage(path);
SettingName();
}
private void InitializeImage(string path)
{
ImageHolder.Source = new BitmapImage(new Uri(path, UriKind.Absolute));
RenderOptions.SetBitmapScalingMode(ImageHolder, BitmapScalingMode.Fant);
ImageHolder.Height = 150;
ImageHolder.Width = 150;
}
private void SettingName()
{
this.name = io.Path.GetFileNameWithoutExtension(path);
NameHolder.Text = name;
NameHolderChange.Text = name;
}
private void NameHolder_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
NameHolder.Visibility = Visibility.Collapsed;
NameHolderChange.Visibility = Visibility.Visible;
}
private void NameHolderChange_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
//CREATING NEW PATH TO RENAMED FILE
string newPath = io.Path.GetDirectoryName(path).ToString()
+ @"\" + NameHolderChange.Text + io.Path.GetExtension(path);
//CREATING COPY OF THE FILE WITH NEW NAME
io.File.Copy(path, newPath);
//REDIRECTING IMAGE TO A NEW SOURCE
InitializeImage(newPath);
//DELETING OLD FILE
//GC.Collect();
//GC.WaitForPendingFinalizers();
io.File.Delete(path);
//REPLACING OLD PATH WITH THE NEW ONE AND
//ACTUALIZING NAME OF THE FILE IN TEXTBOX AND BLOCK
path = newPath;
SettingName();
NameHolder.Visibility = Visibility.Visible;
NameHolderChange.Visibility = Visibility.Collapsed;
}
}
}
}
因此,当用户单击TextBlock时,它会折叠,TextBox变为可见,允许为该文件写一个新名称。当用户按Enter键时,应用程序将生成具有新名称的文件的新副本,图像源重定向到新源,旧文件将被删除。但我无法删除该文件,因为我得到一个未处理的异常:
A first chance exception of type 'System.IO.IOException' occurred in mscorlib.dll
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
Additional information: The process cannot access the file 'E:\foldery\123fgdg\43_460s.jpg' because it is being used by another process.
我在stackoverflow上读到它并且有很多答案,但它们都不像我的。我没有访问该文件的任何流的实例,Image组件不再使用它的路径作为源。 我很确定我的程序阻止访问图像,因为当发生错误并且我尝试从窗口浏览器中删除文件时,我无法访问它,但是当我关闭我的应用程序时,我可以毫无问题地删除它。
还有一段代码 - 这就是我如何获取文件的路径:
string[] unfilteredFiles = Directory.GetFiles(newLocationFolder);
foreach (string file in unfilteredFiles)
{
ImageRep imageRep = new ImageRep(file);
IMGWrapHolder.Children.Add(imageRep);
}