我的wpf应用程序创建了这个临时目录(@“C:\ MyAppTemp \”)。在那个目录里面有下载的图像。 在应用某些点(背景workerCompleted)我不需要任何更多的这个文件夹和文件correspoding,所以我想删除 这个文件夹,所以我试图无法删除文件夹,因为它正在被其他进程使用(我的应用程序)
if (Directory.Exists(@"C:\MyAppTemp\"))
{
IOFileUtils.DeleteDirectory(@"C:\MyAppTemp\", true);
if (!Directory.Exists(@"C:\MyAppTemp\"))
{
DisplayMessage = "Temp files deleted";
}
}
,但我得到这个expcetion后{ “过程不能访问该文件 'C:\ MyAppTemp \客户端1 \ 6.JPG',因为它被另一个 过程。”}
IOFileUtils.cs
public static void DeleteDirectory(string path, bool recursive)
{
// Delete all files and sub-folders?
if (recursive)
{
// Yep... Let's do this
var subfolders = Directory.GetDirectories(path);
foreach (var s in subfolders)
{
DeleteDirectory(s, recursive);
}
}
// Get all files of the folder
var files = Directory.GetFiles(path);
foreach (var f in files)
{
// Get the attributes of the file
var attr = File.GetAttributes(f);
// Is this file marked as 'read-only'?
if ((attr & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
// Yes... Remove the 'read-only' attribute, then
File.SetAttributes(f, attr^FileAttributes.ReadOnly);
}
// Delete the file, RAISES EXCEPTION!!
File.Delete(f);
}
// When we get here, all the files of the folder were
// already deleted, so we just delete the empty folder
Directory.Delete(path);
}
UPDATE 这下面的代码产生异常
var photosOnTempDir = Directory.GetFiles(dirName);
int imgCounter = 0; //used to create file name
System.Drawing.Image loadedImage;
foreach (var image in photosOnTempDir)
{
loadedImage = System.Drawing.Image.FromFile(image);
imageExt = Path.GetExtension(image);
imgCounter++;
var convertedImage = Helpers.ImageHelper.ImageToByteArray(loadedImage);
var img = new MyImage { ImageFile = convertedImage, Name = imgCounter.ToString() };
myobj.Images.Add(img);
}
尝试在'File.SetAttributes'和'File.Delete'方法调用之间添加一些延迟。 – pushpraj 2014-10-08 07:09:43
为什么这么复杂? Directory.Delete(path,true)删除目录以及所有文件和子目录。 http://msdn.microsoft.com/en-us/library/vstudio/fxeahc5f%28v=vs.100%29.aspx – 2014-10-08 07:13:06
当你使用System.Drawing.Image时,为什么这个问题被标记为“WPF”?这是WinForms。无论如何,你得到这个异常的原因是'System.Drawing.Image.FromFile'使文件保持打开状态。使用'FromStream'代替,并在加载图像后立即关闭流,最好用''using'块。 – Clemens 2014-10-08 08:18:24