Search code examples
c#.nettext-parsing

C# - Reading a file to a list and splitting on a delimiter


I have a text file that I need to pull individual values from. An example of this is:

Name: John Doe
Key Length: 3
a90nm84ang9834n
90v84jgseidfrlg
f39048s9ipu4sdd
Random: true

And I would need my output to be something like:

Visitor: John Doe
Key Value: a90nm84ang9834n90v84jgseidfrlgf39048s9ipu4sdd

Right now, I am reading the file into a list and calling on the values individually, but this doesn't allow me to rename the first value of the string (e.g. Name -> Visitor).

My real question is after the file is read into the list, is it possible to further split each of those lines off of a delimiter and reference 1 portion of the pair?

Edit - Here's a sample of the code I'm using, but it doesn't do what I am trying to do:

string path = @"C:\temp\foo.txt";
List<string> lines = File.ReadAllLines(path).ToList();

Console.WriteLine("Filename: " + path);
Console.WriteLine("Length: " + lines[1]); //This outputs "Length: Key Length: 3"

Solution

  • Assuming your data is all formatted the same...how about something like this:

    private static void ParseDataFile(string dataFile)
    {
        var lines = File.ReadAllLines(dataFile);
    
        for (var i = 0; i < lines.Length; i++)
        {
            if (lines[i].Contains("Name"))
            {
                Console.WriteLine($"Visitor: {lines[i].Remove(0, 6)}");
                var keyLineCount = Convert.ToInt32(lines[++i].Remove(0, 12));
                string key = string.Empty;
    
                for (var j = 0; j < keyLineCount; j++)
                {
                    key += lines[++i];
                }
    
                i++;
                Console.WriteLine($"Key Value: {key}");
            }
        }
    }
    

    To answer your specific question: Yes, it is possible to split strings on various characters at different times:

    string s = "1234567890";
    string[] parts1 = s.Split('5'); // 2 parts "1234" and "67890"
    string[] parts2 = parts1[1].Split('7','9'); // 3 parts "6", "8" and "0"
    

    etc.