我的wpf应用创建了这个临时目录(@“C:\ MyAppTemp \”)。在该目录中有下载的图像。 在应用程序中的某个点(后台workerCompleted)之后我不再需要这个文件夹和对应的文件,所以我想要删除 这个文件夹,所以我试过
if (Directory.Exists(@"C:\MyAppTemp\"))
{
IOFileUtils.DeleteDirectory(@"C:\MyAppTemp\", true);
if (!Directory.Exists(@"C:\MyAppTemp\"))
{
DisplayMessage = "Temp files deleted";
}
}
但是我得到了这个expcetion {“该进程无法访问文件'C:\ MyAppTemp \ Client1 \ 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);
}
更新 以下代码引发异常
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);
}
答案 0 :(得分:0)
确保我们对涉及这些文件的任何内容使用“使用”。你可能持有一些尚未处理其中一个文件的句柄,因此 - 阻止你删除它。