1

how to delete a zip file after copying into another folder...I am getting exception while deleting..It is saying that "The file is being used by another process".

string pathString1 = FullFilePath;
string sourceFileName = Path.GetFileName(pathString1);
string foldername = Path.GetDirectoryName(pathString1);
string pathString = Path.Combine(foldername, "Uploaded");
if (!System.IO.Directory.Exists(pathString))
{
    System.IO.Directory.CreateDirectory(pathString);
    string destFile = System.IO.Path.Combine(pathString, sourceFileName);
    File.Copy(pathString1, destFile);

    File.Delete(pathString1);
    File.Delete(FileName);
}
Jcl
  • 27,696
  • 5
  • 61
  • 92
Pinky
  • 33
  • 4

3 Answers3

2

If you decompress the zip-file, then do this in a using block or .Dispose() the object that is responsible for decompressing. What lib are you using?

Radinator
  • 1,048
  • 18
  • 58
2

To prevent the locking of files, the using statement will release the file when it's done with the operation:

using (FileStream stream = File.Open("path to file", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
    ...
}

Then again, if you're deleting the file right after you copy it, then why not just move it?

File.Move(from, to);
Community
  • 1
  • 1
Daniel Minnaar
  • 5,865
  • 5
  • 31
  • 52
  • tried but der also same exception.. could not access because the file is being used by another process.. – Pinky Jul 28 '16 at 09:58
0

since there is this theory that a virus checker goes into your .zip file, you could re-try waiting for it to finish with retries

string pathString1 = FullFilePath;
string sourceFileName = Path.GetFileName(pathString1);
string foldername = Path.GetDirectoryName(pathString1);
string pathString = Path.Combine(foldername, "Uploaded");
if (!System.IO.Directory.Exists(pathString))
{
    System.IO.Directory.CreateDirectory(pathString);
    string destFile = System.IO.Path.Combine(pathString, sourceFileName);
    File.Copy(pathString1, destFile);

    int itries = 0;
    int maxtries = 30;    //suitable time of retrying
    while (itries++ < maxtries)
    {   
        try 
        {
            File.Delete(pathString1);
            itries = 999999;
        }
        catch (Exception ex)
        {
          if (itries > maxtries) throw ex;  
          Thread.Sleep(1000);
        }       

    }

    //File.Delete(FileName);
}
Cato
  • 3,652
  • 9
  • 12