简体   繁体   中英

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'?

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://docs.microsoft.com/en-us/dotnet/api/system.string.startswith?view=netcore-3.1 https://docs.microsoft.com/en-us/dotnet/api/system.io.fileinfo.name?view=netcore-3.1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM