get file date from filename

jn93 671 Reputation points
2022-11-26T12:46:33.19+00:00

Hi All, I have the SSIS package to extract the data from txt file. One of the task in my SSIS is using script task to get filedate,filename and etc. Previously I have a filename like below in Example 1. Hence, I use below shared C# script to get the date from the filename. If the filename got changes like below in Example 2, how can I do changes in the C# script to get the date from filename? Kindly please help.

264385-image.png

            string FileName = System.IO.Path.GetFileName(Dts.Variables["User::v_FILEPATH"].Value.ToString());  
            Dts.Variables["User::v_FILENAME"].Value = FileName;  
            string FilenameWoutExt = System.IO.Path.GetFileNameWithoutExtension(Dts.Variables["User::v_FILENAME"].Value.ToString());  
            string dateValue = FilenameWoutExt.Substring(FilenameWoutExt.LastIndexOf('_')+1);  
            Dts.Variables["User::v_FILEDATE"].Value = dateValue;  
SQL Server Integration Services
SQL Server Integration Services
A Microsoft platform for building enterprise-level data integration and data transformations solutions.
2,510 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,605 questions
0 comments No comments
{count} votes

Accepted answer
  1. Yitzhak Khabinsky 25,726 Reputation points
    2022-11-27T00:08:34.073+00:00

    Hi @jn93 ,

    The .Split() method is very handy for your scenario.
    Check it out below.

    c#

    void Main()  
    {  
     string FilenameWoutExt = "RL_TB_COMCN_TMI_20220801_0000";  
      
     // break string into a string array of tokens  
     string[] tokens =  FilenameWoutExt.Split('_');  
     string dateValue = tokens[tokens.Count()-2] + tokens[tokens.Count()-1];  
    }  
    

    Output

    202208010000  
    

1 additional answer

Sort by: Most helpful
  1. P a u l 10,496 Reputation points
    2022-11-26T13:05:25.3+00:00

    Is the suffix always "_0000"? If so you could just trim it off:

       string FilenameWoutExt = System.IO.Path.GetFileNameWithoutExtension(Dts.Variables["User::v_FILENAME"].Value.ToString());  
         
       if (FilenameWoutExt.EndsWith("_0000")) {  
       	FilenameWoutExt = FilenameWoutExt.Substring(0, FilenameWoutExt.Length - 5);  
       }  
         
       string dateValue = FilenameWoutExt.Substring(FilenameWoutExt.LastIndexOf('_')+1);  
         
       ...  
    

    That way both formats can be supported.