2

I'd like to delete a file like this:

List<FichierModels> liste = fichiers.GetFichiersFromDirectoy(_directory_id);

//supprimer les fichiers expirés
foreach (Models.FichierModels fich in liste)
{

    if (fich.Expiration_date < DateTime.Now)
    {
        System.IO.File.Delete(fich.Url);
        fich.Delete_fichier(fich.Id);
    }
}

 public List<FichierModels> GetFichiersFromDirectoy(int _id_dir)
        {
            List<FichierModels> l = new List<FichierModels>();
            Data.Connect();
            using (Data.connexion)
            {
                string queryString = @"select Id, Id_directory, Url, Upload_date, Last_download, Downloads_count, Taille, Expiration_date, Name from Fichier where Id_directory = @Id_directory ";
                SqlCommand command = new SqlCommand(queryString, Data.connexion);
                command.Parameters.AddWithValue("@Id_directory", _id_dir);
                try
                {
                    SqlDataReader reader = command.ExecuteReader();
                      do
                    {

                        while (reader.Read())
                        {
                            FichierModels fichier = new FichierModels();
                            fichier.Id = reader.GetInt32(0); 
                                fichier.Id_directory = reader.GetInt32(1);
                                fichier.Url = reader.GetString(2); 
                                fichier.Upload_date = reader.GetDateTime(3); 
                                fichier.Last_download = reader.GetDateTime(4);
                                fichier.Downloads_count = reader.GetInt32(5);

                                fichier.Taille = reader.GetDouble(6); 
                                fichier.Expiration_date = reader.GetDateTime(7);
                                fichier.Name = reader.GetString(8) ;
                            l.Add(fichier);

                        }
                    } while (reader.NextResult());

                    return l;



                }
                catch { return null; }

            }
        }

i used this function :

 public void ExtractArchive(string zipFilename, string ExtractDir)
         {
             ZipInputStream zis = null;
             FileStream fos = null;

             try
             {
                 zis = new ZipInputStream(new FileStream(zipFilename, FileMode.Open, FileAccess.Read));
                 ZipEntry ze;

                 // on dezippe tout dans un rep du nom du zip, pas en bordel
                 Directory.CreateDirectory(ExtractDir);

                 while ((ze = zis.GetNextEntry()) != null)
                 {
                     if (ze.IsDirectory)
                     {
                         Directory.CreateDirectory(ExtractDir + "\\" + ze.Name);
                     }
                     else
                     {
                         if (!Directory.Exists(ExtractDir + "\\" + Path.GetDirectoryName(ze.Name)))
                         {
                             Directory.CreateDirectory(ExtractDir + "\\" + Path.GetDirectoryName(ze.Name));
                         }

                         fos = new FileStream(ExtractDir + "\\" + ze.Name, FileMode.Create, FileAccess.Write);
                         int count;
                         byte[] buffer = new byte[4096];

                         while ((count = zis.Read(buffer, 0, 4096)) > 0)
                         {
                             fos.Write(buffer, 0, count);
                         }
                     }
                 }
             }
             finally
             {
                 if (zis != null) zis.Close();
                 if (fos != null) fos.Close();
             } 
         }

but I have an exception that indicates that the file is used by another process. How can I pause this process, delete the file and then continue the process?

Lamloumi Afif
  • 8,941
  • 26
  • 98
  • 191
  • you should better try to understand which process, and why, lock this file. [Process explorer](http://technet.microsoft.com/sysinternals/bb896653.aspx) may help! Killing threads or process can cause more damages than solving your issue. – Steve B May 31 '13 at 09:42
  • possible duplicate of [How do I delete a file which is locked by another process in C#?](http://stackoverflow.com/questions/1040/how-do-i-delete-a-file-which-is-locked-by-another-process-in-c) – Steve B May 31 '13 at 09:50
  • 1
    Could you also add the `GetFichiersFromDirectoy` method's body? – Alex Filipovici May 31 '13 at 09:52
  • Is it very probable that you are locking the file from your own application? – Alex Filipovici May 31 '13 at 10:11

3 Answers3

2

You can use this program to check which process has locked the file you are trying to delete. You will need to kill the process which locked the file in order to be able to delete the file. Some sample code to kill the process:

    Process tool = new Process();
    tool.StartInfo.FileName = "handle.exe";
    tool.StartInfo.Arguments = fileName+" /accepteula";
    tool.StartInfo.UseShellExecute = false;
    tool.StartInfo.RedirectStandardOutput = true;
    tool.Start();           
    tool.WaitForExit();
    string outputTool = tool.StandardOutput.ReadToEnd();

    string matchPattern = @"(?<=\s+pid:\s+)\b(\d+)\b(?=\s+)";

    foreach(Match match in Regex.Matches(outputTool, matchPattern))
    {
        Process.GetProcessById(int.Parse(match.Value)).Kill();
    }

Replace the matchPattern with your pattern, you should be able to kill that process which has locked your file.

lex87
  • 1,276
  • 1
  • 15
  • 33
1

Pausing the process will not help you. You have to stop using the file in the process or if you can't close the process. You are using a web interface, so you can show a message to the user which file blocks the deletion of the files, and give him the option to retry. If the file is unlocked (process released the lock or the process is closed) the deletion will succeed. If not he can retry again.

One think you should ask yourself is why you need to delete a file which is still in use. It seems a bit odd to me.

Peter
  • 27,590
  • 8
  • 64
  • 84
1

I don't know if it's your case, but sometimes happened to me that an exception like yours have been thrown because i didn't call the method Close() when opening the file in the same process. Try to check where you first use the file

Nico.S
  • 753
  • 8
  • 12