Reading a section of text file between tokens in C#

Al S 1 Reputation point
2022-12-07T00:47:59.17+00:00

I have a text file that is bounded by tokens that define a section of the file. For example. A start token string is "2D FILES". The end token is "END". Each line in between the tokens can be read into a dictionary key and value. How to read the relevant lines of code that are only in between the two tokens:

Test File
Description

2D FILES
C:\Temp\Temp123 123
C:\Temp\Temp321 321
C:\Temp\Temp456 4564
END

TestFile
Footer
Footer2
Footer3

Developer technologies | C#
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Jack J Jun 25,296 Reputation points
    2022-12-07T01:50:00.323+00:00

    @Al S , Welcome to Microsoft Q&A, you could use the index of start token and end token to get a section of textfile.

    Here is a code example you could refer to.

     var file = File.ReadAllLines("test.txt").ToList();  
                int startindex = file.IndexOf("2D FILES");  
                int endindex = file.IndexOf("END");  
                var result = file.Skip(startindex + 1).Take(endindex-startindex-1);  
                Dictionary<string, int> dic = new Dictionary<string, int>();  
                foreach (var item in result)  
                {  
                    dic.Add(item.Split(' ')[0], Convert.ToInt32(item.Split(' ')[1]));  
                }  
                foreach (var item in dic)  
                {  
                    Console.WriteLine("key is {0} and value is {1}",item.Key,item.Value);  
                }  
    

    Tested result:

    267900-image.png

    Hope this could help you.

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  2. George Tyrebyter 46 Reputation points
    2022-12-07T02:41:39.303+00:00

    Hi Jack.

    Problem at line 8:
    System.FormatException
    HResult=0x80131537
    Message=Input string was not in a correct format.

    Trying to see why.

    Thanks for the sample


  3. George Tyrebyter 46 Reputation points
    2022-12-20T12:06:41.49+00:00

    Hello,

    I eventually solved the issue with the trailing spaces:

    string[] seperators = { " ", "\t" }; // this provides the means to identify the spaces between key and value.
    TwoD_List.Add(item.Split(seperators, StringSplitOptions.RemoveEmptyEntries)[0],
    Convert.ToInt32(item.Split(seperators, StringSplitOptions.RemoveEmptyEntries)[1]));

    0 comments No comments

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.