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,702 questions
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Yitzhak Khabinsky 26,586 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,761 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.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.