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.

4 comments:

  1. I think this is actually a very good piece of information about SSIS and really shows and helps people find solution to a very common problem.

    SSIS Postgresql Read

    ReplyDelete
  2. many thanks, this really help me and it's very easy to apply.
    I use it to delete files in shared file.

    ReplyDelete
  3. Just thinking can I use this example to Delete folders instead of the files.

    ReplyDelete

If you have any doubt, please let me know.

Popular Posts