Question

I have a foreach loop that has try catch and finally. it goes through files in a folder and finally deletes them all....but now if i have two files, as it is deleting all( i need to delete all because of app functionality) it will not go though second file. is it possible to let foreach loop finish then delete all files in foreach method here is an example:

foreach (DirectoryInfo directory in directories)
{
    foreach (FileInfo file in directory.GetFiles("*.csv"))
    {
        try
        {
           //do something with file

        }

        catch (Exception e)
        {
            //catch exception
        }
        finally
        {
            if (!IsFileLocked(file))
            {
                string[] files = Directory.GetFiles(@"C:\Test");
                foreach (string filetoDelete in files)
                {
                    File.Delete(filetoDelete);
                }
            }
        }
    }
}

hope it is clear enough.

Was it helpful?

Solution

I'm not very sure if I'm right understood what you're asking for, but to me it seems solution pretty trivial, like this:

foreach (DirectoryInfo directory in directories)
{
    foreach (FileInfo file in directory.GetFiles("*.csv"))
    {
        try
        {
            //do something with file

         }

         catch (Exception e)
         {
               //catch exception
          }
     }

     foreach(FileInfo fileToDeleteInfo...)
     {
          try
          {
               if (!IsFileLocked(fileToDeleteInfo))
               {
                  string[] files = Directory.GetFiles(@"C:\Test");
                  foreach (string filetoDelete in files)
                  {
                       File.Delete(filetoDelete);
                  }
                }


            }
          catch(...)
          {... }
     }

In other words, move file deletion from the second (nested) foreach into the new one.

If this is not what you're asking for, please clarify.

OTHER TIPS

Your code:

  1. Loops through given set of directories and for each of them:
  2. Gets "*.csv" files in that dir and with each file:
  3. Does something and then:
  4. Deletes files from "C:\Test".

Shouldn't you be deleting the file you just processed, or at least files from the dir you are currently processing, not files from "C:\Test"?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top