내 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
왜 그렇게 복잡합니까? Directory.Delete (path, true) 디렉토리와 모든 파일 및 하위 디렉토리를 제거합니다. http://msdn.microsoft.com/en-us/library/vstudio/fxeahc5f%28v=vs.100%29.aspx –
'System.Drawing.Image'를 사용할 때 왜이 질문에'WPF' 태그가 붙어 있습니까? 그것은 WinForms입니다. 어쨌든, 당신이 예외를 얻는 이유는'System.Drawing.Image.FromFile'이 파일을 열어 두었 기 때문입니다. 대신에'FromStream'을 사용하고 이미지를 로딩 한 직후 스트림을 닫으십시오. 가능하면'using' 블록을 사용하십시오. – Clemens