Skip to main content

Delete files older than retention period from specified folder using Script Task in SQL Server - SSIS

Earlier we have seen in the Delete file using Script Task and file deletion using File System Task in SSIS. We have directly written the logic to get the files and delete from specified folder in the script for the Script Task. For File System Task we have Used Foreach Loop Container and variables to hold file names which are passed from earlier stage one by one and then finally used by the File System Task to delete it.

Here we have same, but don't delete all the files inside pass folder, but get deleted files which are older than the specified days. This is nothing but minor change in the script where we pass the folder path and retention period. Let's start the steps as follow,

1. Let check the files from the target folder.


2. Drag and drop Script Task.


3. Open script editor from the properties.


4. Apply attached script in editor which have additional logic with condition to check the file last modified date and check if older than specified retention period or not.


Please note here we need to import system.IO namespace.

5. Turn on the final step and run package. Files older than the specified retention period to get deleted.

You can also find script code here,

--// You need to apply below one line in "namespaces" region.
using System.IO;

--//You need to apply below lines inplace of  // TODO: Add your code here
int RetentionPeriod = 3;
string directoryPath = @"E:\ImagesBackup";
string[] oldFiles = System.IO.Directory.GetFiles(directoryPath, "*.png");
     foreach (string currFile in oldFiles)
            {
                FileInfo currFileInfo = new FileInfo(currFile);
                if (currFileInfo.LastWriteTime < (DateTime.Now.AddDays(-RetentionPeriod)))
                {
                    currFileInfo.Delete();
                }
            }
Hope you liked this post. Stay tuned for more.

Comments

  1. The post is great, the content is clear and easy to understand. Many Thanks

    ReplyDelete

Post a Comment