我的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