Unable to delete Package File after an exception during opening

I am creating a package file and fill content in it. For some reason, the package will get corrupt.

I wanted to handle this in this way:

try
{
  using (Package archivePkg = Package.Open("TestLogFile.zip", FileMode.OpenOrCreate))
  { ...
  } //end of using
} //end of try
catch (IndexOutOfRangeException ex)
{
File.Delete("TestLogFile.zip"); // IOException
}
//also at this point I am not able to delete the file

The exception of a corrupt zip file is caught but I am not able to delete the file: It is occupied by another process (my program!). I tested a lot of variants with using / try/catch but without success!
Mike2010Asked:
Who is Participating?
 
Carlos VillegasConnect With a Mentor Full Stack .NET DeveloperCommented:
Ok, have you tried the posted code? still the same problem?
0
 
Carlos VillegasFull Stack .NET DeveloperCommented:
Hello, what if you try this?:
try
{
    using (System.IO.FileStream fs = System.IO.File.Open("TestLogFile.zip", FileMode.OpenOrCreate))
    {
        using (Package archivePkg = Package.Open(fs, FileMode.OpenOrCreate))
        {
            // Etc...
        }
    }
}
catch (IndexOutOfRangeException ex)
{
    if (System.IO.File.Exists("TestLogFile.zip"))
        System.IO.File.Delete("TestLogFile.zip");
}

Open in new window

0
 
Carlos VillegasFull Stack .NET DeveloperCommented:
BTW, is strange that your file is being corrupt, check that only one thread/process is writing on it.
0
Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

 
Mike2010Author Commented:
Thank you for your answers!

The file is existing (I can see the lock with MS Process Explorer), the test program was written as a windows console application so there is only one thread.
0
 
Mike2010Author Commented:
Sorry, I did not look sharp to your code: Your suggestion is right: If you are separating the file open and Package.Open process then I am able to delete the file.

Very clever, thank you!
0
 
Carlos VillegasFull Stack .NET DeveloperCommented:
Glad to help, that means there's a bug on the Package.Dispose method, this must guarantee the release of all the resources, but it's not doing this.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.