Click here to Skip to main content
14,691,895 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello friends,

I am facing some problem when i am delete .XMl file in a physically path then if a file in under process then it will be not deleted or other file are delete.

So i am describe my code

public static void DeleteUsedXMl()

      {
          try
          {
          string PhyPath = ConfigurationManager.AppSettings["PhyPath"];//This is my physically address path
          string filesToDelete = "*.xml";
    string[] fileList = 
System.IO.Directory.GetFiles(PhyPath + "Feeds\\", filesToDelete);


       foreach (string FileFullName in fileList)
          {
if (!CheckIfFileIsBeingUsed(FileFullName))
              {
               System.IO.File.Delete(FileFullName);          
          }
  }
          catch (Exception)
          {

              throw;
          }
}



private static bool CheckIfFileIsBeingUsed(string FileFullName)
       {
           try
           {
              FileStream fs = File.Open(FileFullName, FileMode.Open, FileAccess.Read, FileShare.None);
               fs.Close();
}
           catch (Exception exp)
           {
               return true;
           }

           return false;

       }





So kindly give me a appropriate suggestion .

Thanks.

sanwar
Posted

1 solution

Just delete in a try/catch block :
...       
          foreach (string FileFullName in fileList)
          {
              try
              {
               System.IO.File.Delete(FileFullName);   
              }
              catch {}
          }
   
Comments
sanwar_mal_jat 2-Jul-12 7:08am
   
Thanks for reply,

But it will be deleted all of the existing file if they are use in process like (if file open or in a other process).
Plz revise my code.

Thanks
Mehdi Gholam 2-Jul-12 7:17am
   
If the file is opened by someone else then you will get an exception and it won't delete that file.
sanwar_mal_jat 2-Jul-12 7:21am
   
ya file open by some one and not stop the process ,when delete all files except opened file.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900