Search code examples
c#export-to-csv

C# Write Csv file columns from string lines


so I am writing a csv file from a text file but there is many split formats that I am not sure how to figure it out

here is an example from the text file data

{Sll} 2022 Oct 04 14:55:06.838 [i] [Column 2][column 3] Loading text...

{Sll} 2022 Oct 04 14:55:06.838 [i] [Column 2][column 3 ] Loading text....

{Sll} 2022 Oct 04 14:55:06.839 [i] [Column 2][column 3 ] Loading text....

i need to select column 1 which is full datetime data (2022 Oct 04 14:55:06.838)

column 2 is the text Column 2,

column 3 is column 3

what i tried to select the date and time was and still not getting the correct data

any help please? i know i need to use lots of splitting and converting but not sure what is missed

 Match match = Regex.Match(TextContents.GetLineText(i), @"\d{4}\/\d{3}\/\d{2}");

 string date = match.Value;
 if (!string.IsNullOrEmpty(date))
    {
     var dateTime = DateTime.ParseExact(date, "yyyy MMM d H:m:s.fff",  CultureInfo.CurrentCulture);
     Console.WriteLine(dateTime.ToString());
      }

     writer.WriteLine(date);

and

newfile.Select(line => DateTime.ParseExact(line.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries)[2], "yyyy MMM d H:m:s.fff", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal));
DateTime time = DateTime.ParseExact(TextContents.GetLineText(i).Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[2], "yyyy MMM d H:m:s.fff", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal);


Solution

  • solved using the below code

     string delimiter = "  ";
                                int dateTimeLength = 24;
                                int dataTimeStart = TextContents.GetLineText(i).IndexOf(delimiter);
                                string dateTimeString = TextContents.GetLineText(i).Substring(dataTimeStart + delimiter.Length, dateTimeLength);
    
    writer.Write(dateTimeString);