How to delete all the all files from folder EXCEPT LATEST file?

Hi All,

I want to delete all the old file from the folder except the latest file.How to delete all the all files from folder EXCEPT the LATEST file?

Regards,
Ritesh

Hi @Ritesh_Burman

First, get all the file names from the specified folder into an array like this:

fileList = Directory.GetFiles("Your Folder Path")

Then, determine the latest file like this:

latestFile = fileList.OrderByDescending(Function(x) New FileInfo(x).LastWriteTime).FirstOrDefault()

Now, you can loop through each array element & check if the current file name is equal to the latestFile, if not, you can use the Delete File activity to delete the current file.

Hope this helps,
Best Regards.

Hi @Ritesh_Burman

Try this

  1. Assign activity:

    • To: folderPath
    • Value: “C:\Path\to\Your\Folder”
  2. Assign activity:

    • To: filesList
    • Value: Directory.GetFiles(folderPath).ToList()
  3. Assign activity:

    • To: latestFile
    • Value: filesList.OrderByDescending(Function(x) New FileInfo(x).LastWriteTime).First()
  4. For Each activity:

    • TypeArgument: String
    • Values: filesList
  5. If activity:

    • Condition: item <> latestFile
  6. Delete File activity:
    - FilePath: item

Hope it helps!!

Regards,

@Ritesh_Burman

You can do as below

  1. For each file in folder and order by last modified date
  2. Use if condition to ignore first file where currentindex is zero
  3. Else delete the file

Hope this helps

cheers

Hi @Anil_G ,

This is not working actually , its not giving the current index.equals(0) as True. rather delting all the files.
Could u please check this one?

Regards.,
Ritesh

Its done , index issue.

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.