Monday, 7 October 2019

Delete 60 Days Old Files from the Archive Folder Using Script Task in SSIS


Generally, we are loading the file data from the source folder and after file loaded we are doing archive these files in the archive folder. The business wants to delete the 60 days old files from the archive folder.
Let’s see in this demo how we will do.
Below is the archive folder.
 

Highlighted files are older than 60 days.
Taking Script task
 

Taking some variable
                                 

In script task we need to write C# code to delete the older files.
string DirectoryPath = Dts.Variables["User::Archive_Folder"].Value.ToString();
            int Number_of_day = (int)Dts.Variables["User::Number_of_day"].Value;

            if (System.IO.Directory.Exists(DirectoryPath))
            {
                string[] files = System.IO.Directory.GetFiles(DirectoryPath);
                foreach (var file in files)
                {
                    System.IO.FileInfo finf = new System.IO.FileInfo(file);
                    TimeSpan File_age = DateTime.Now.Subtract(finf.LastWriteTime);
                    if ((int)File_age.TotalDays > Number_of_day)
                        //remove old file
                        System.IO.File.Delete(file);
                }
            }


Now package is ready to run.
Before running this package


After running the package.


See the archive folder


Get the expected result.

Popular Posts