Substring C# Issue

John K 186 Reputation points
2020-09-09T11:44:19.283+00:00

Hi
I am working on a C# code where I have a requirement to identify the filename in SSIS Package

The files which I receive are in the following formats

FL_NamePart1.20200909
FL_NamePart1_NamePart2_20200909
FL_NamePart1_NamePart2_NamePart3_20200909

Part before first underscore is FL
Part after last udnerscore is datetime

So I use the following logic to get the filename

string filename =SourceFileName.Substring(SourceFileName.IndexOf('') +1);
string FinalFilename=filename .Substring(0,filename .LastIndexOf("
"));

This is working fine
However,
There are 2 files says FILE M , FILEN which are coming in this pattern

FL_FILEM_01_20200909
FL_FILEM_02_20200909

FL_FILEN_01_20200909
FL_FILEN_02_20200909

I want my code to deduce the filenames as FileM, FileN

The logic used in first example will not work as it wil evaluate filename as FILEM_01

I can have 2 set of logics

However is it possible to have just 1 code to handle both the input string patterns

Thanks

SQL Server Integration Services
SQL Server Integration Services
A Microsoft platform for building enterprise-level data integration and data transformations solutions.
2,502 questions
0 comments No comments
{count} votes

Accepted answer
  1. Yitzhak Khabinsky 25,721 Reputation points
    2020-09-09T13:44:29+00:00

    Please try the following solution. I heavily commented it, so it should be clear how it works.

    void Main()
    {
     string SourceFileName = "FL_FILEM_01_20200909";
     //SourceFileName = "FL_NamePart1_NamePart2_NamePart3_20200909";
    
     string filename = SourceFileName.Substring(SourceFileName.IndexOf("_") + 1);
     string FinalFilename = filename.Substring(0, filename.LastIndexOf("_"));
    
     // find last token
     string LastToken = FinalFilename.Split('_').Last();
    
     // check if last token is numeric
     if (Int32.TryParse(LastToken, out int j))
     {
     // count all tokens
     int counter = FinalFilename.Split('_').Count();
     // assemble all back except last token
     FinalFilename = string.Join("_", FinalFilename.Split('_').Take(counter-1));
     }
    
     Console.WriteLine(FinalFilename);
    }
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Leon Laude 85,716 Reputation points
    2020-09-09T11:59:18.563+00:00

    Hi,

    I would try asking in the dedicated C# forums over here:
    https://social.msdn.microsoft.com/Forums/en-US/home?forum=csharpgeneral

    https://forums.asp.net/37.aspx/1?C


    (If the reply was helpful please don't forget to upvote or accept as answer, thank you)

    Best regards,
    Leon

    0 comments No comments