Error deleting directory (file being used)

1

I am compacting a folder and then deleting the folder that already existed. The problem is that in some situations, I fall into an exception stating that a file in the folder is still being used:

ZipFile.CreateFromDirectory(sDiretorioZip, string.Concat(sDiretorioZip, ".zip"), CompressionLevel.Fastest, true);
DirectoryInfo dir = new DirectoryInfo(sDiretorioZip);
Directory.Delete(sDiretorioZip, true);
    
asked by anonymous 13.09.2017 / 00:40

2 answers

0

Add a System.Threading.Thread.Sleep(int32); before deleting the file. What happens is that sometimes the folder being compressed did not have time to be closed by ZipFile , so the application will return a folder exception in use, making it impossible to delete it. When you add the method described at the beginning of the response, your application will 'sleep' for the desired time (in milliseconds) which is exactly the time it takes for ZipFile to finish its service and the deletion continues normally. Note:

ZipFile.CreateFromDirectory(sDiretorioZip, string.Concat(sDiretorioZip, ".zip"), CompressionLevel.Fastest, true);
DirectoryInfo dir = new DirectoryInfo(sDiretorioZip);
System.Threading.Thread.Sleep(100);
Directory.Delete(sDiretorioZip, true);

@EDIT: As a request, a code that excludes only when the compression is complete.

ZipFile.CreateFromDirectory(sDiretorioZip, string.Concat(sDiretorioZip, ".zip"), CompressionLevel.Fastest, true);
DirectoryInfo dir = new DirectoryInfo(sDiretorioZip);
while (true)
{
    System.Threading.Thread.Sleep(50); //Um timing opcional pra não utilizar tanto da máquina
    try
    {
        Directory.Delete(sDiretorioZip, true); //Tentativa de exclusão, se o arquivo estiver em uso ele irá retornar uma exceção e o código irá se digirir ao bloco catch(){}
        break; //Sai do loop infinito após a exclusão do arquivo não retornar erro
    }
    catch (IOException err)
    {
        //Se der uma exceção, arquivo em uso por exemplo, ele tenta excluir novamente, até conseguir.
        continue;
    }
}
//Continuação do seu código
    
13.09.2017 / 01:42
0

Follow the new code, even giving the error, even after the dispose ...

    
13.09.2017 / 21:35