Error deleting directory(file being used)

Asked

Viewed 417 times

1

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

ZipFile.CreateFromDirectory(sDiretorioZip, string.Concat(sDiretorioZip, ".zip"), CompressionLevel.Fastest, true);
DirectoryInfo dir = new DirectoryInfo(sDiretorioZip);
Directory.Delete(sDiretorioZip, true);
  • 3

    Tried to give a Thread.Sleep?

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, soon, the application will return a folder exception in use, making it impossible to delete it. By adding the method described at the beginning of the reply your app will 'sleep' for the desired time (in milliseconds) which is exactly the time required for ZipFile end your service and delete continue 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 requested, a code that excludes only when compression is finished.

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
  • I tried. I’m sorry, I should have said that. I even spent exactly the same time. You know if there is a way to check if the compaction is finished?

  • I searched the documentation and found nothing related to the end of the compaction, but it has how to know this in a way 'gambiarra', but it is functional, I edited the topic, test please.

  • So...I did it another way, to try not to gambiarra. The problem is that it still gives the error that the file is being used. Even after the Dispose

0

Follow the new code, theinserir a descrição da imagem aquistill giving error, even after Dysplasia...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.