我有一个方法,具有以下逻辑:
这是问题开始的地方。当用户想要重复操作时,imagebox1和imagebox2会分配给他们的图片。步骤#0失败,错误
The process cannot access the file '03933.tiff' because it is being used by another process.
我的尝试是:
private void CopyImage_Click(object sender, EventArgs e)
{
string currentPath = Directory.GetCurrentDirectory();
string pathInput = currentPath + "\\Input";
string pathOutput = currentPath + "\\Output";
if (pictureBoxInput.Image != null) {
pictureBoxInput.Image = null;
pictureBoxInput.Dispose();
}
if (pictureBoxOutput.Image != null) {
pictureBoxOutput.Image = null;
pictureBoxOutput.Dispose();
}
System.IO.DirectoryInfo di = new DirectoryInfo(pathInput + "\\");
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
System.IO.DirectoryInfo dia = new DirectoryInfo(pathOutput + "\\");
foreach (FileInfo file in dia.GetFiles())
{
file.Delete();
}
但程序尝试删除文件时仍然出现相同的错误。
答案 0 :(得分:1)
我建议改变:
if (pictureBoxInput.Image != null) {
pictureBoxInput.Image = null;
pictureBoxInput.Dispose();
}
为:
if (pictureBoxInput.Image != null) {
var existingFile = pictureBoxInput.Image;
pictureBoxInput.Image = null;
existingFile?.Dispose();
}
和pictureBoxOutput
问题是你的现有代码正在处理错误的东西 - 你正在处置PictureBox
而不是Image
(并且Image
是拿着文件锁的东西。)