Search code examples
c#sql-serverssissql-server-2014

SSIS Script Task Delete Files using a Wildcard


Using SQL Server 2014 \ VS 2019. I have the below C# script task to delete files in a folder older than x number of days, and this works.

    public void Main()
    {
        int RetentionPeriod = Convert.ToInt32(Dts.Variables["$Package::FileRententionDays"].Value.ToString());
        string directoryPath = Dts.Variables["CSV_ArchivePath"].Value.ToString();
        string[] oldFiles = System.IO.Directory.GetFiles(directoryPath, "*.*");

        foreach (string currFile in oldFiles)
        {
            FileInfo currFileInfo = new FileInfo(currFile);

            if (currFileInfo.LastWriteTime < (DateTime.Now.AddDays(-RetentionPeriod)))
            {
                currFileInfo.Delete();
            }
        }

        Dts.TaskResult = (int)ScriptResults.Success;
    }

However, how do I modify to just say, delete all files in the directory where the filenames begins with 'ABC'?


Solution

  • Define your start with "PREFIX" in a string something like StartsWithPrefix. Use the String.StartsWith Method to check if the FileInfo Name has the defined prefix needed to meet the requirements.

                int RetentionPeriod = Convert.ToInt32(Dts.Variables["$Package::FileRententionDays"].Value.ToString());
                string directoryPath = Dts.Variables["CSV_ArchivePath"].Value.ToString();
                string[] oldFiles = System.IO.Directory.GetFiles(directoryPath, "*.*");
    
                string StartsWithPrefix = "ABC";
    
                foreach (string currFile in oldFiles)
                {
                    FileInfo currFileInfo = new FileInfo(currFile);
    
                    if (currFileInfo.LastWriteTime < (DateTime.Now.AddDays(-RetentionPeriod)) 
                        && currFileInfo.Name.StartsWith(StartsWithPrefix))
                    {
                        currFileInfo.Delete();
                    }
                }
    

    https://learn.microsoft.com/en-us/dotnet/api/system.string.startswith?view=netcore-3.1 https://learn.microsoft.com/en-us/dotnet/api/system.io.fileinfo.name?view=netcore-3.1