My wpf app creates this temp directory (@"C:\MyAppTemp\"). Inside that directory there are downloaded images. After certain point in app (background workerCompleted) I dont need any more this folder and correspoding files, so I want to deleted this folder, so I tried
if (Directory.Exists(@"C:\MyAppTemp\"))
{
IOFileUtils.DeleteDirectory(@"C:\MyAppTemp\", true);
if (!Directory.Exists(@"C:\MyAppTemp\"))
{
DisplayMessage = "Temp files deleted";
}
}
but I'm getting this expcetion {"The process cannot access the file 'C:\MyAppTemp\Client1\6.jpg' because it is being used by another process."}
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 This code below raises exception
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);
}