Search code examples
c#readfiletext-processing

How to find a word from a text file and then read the next word after it on C#


Ok I've got a txt file named "info.txt" which includes the following text:

[entry]
title = Hello World
info = sometext
number = 0
available = -1

[entry]
title = All Vids
info = somemoretext
number = 1
available = 0

[entry]
title = All pics
info = somedifferenttext
number = 2
available = -1

[entry]
title = all music
info = differenttext
number = 3
available = 0

On C# What I want to do is open this file and search for "title = " and then get any words after it and then put it inside a text box. So for example, after it looks for "title = " I want it to put "Hello World" inside textbox1. Then if there is another "title = " which would be "All Vids" I want to put it inside textbox2. The same should be done if there are more instances of "title = " which should be placed into textbox3, textbox4 and so on.

This is what I worked on which I found from another answer:

        private void button1_Click(object sender, EventArgs e)
    {
        List<List<string>> groups = new List<List<string>>();
        List<string> current = null;
        foreach (var line in File.ReadAllLines(@"C:\Users\Rohul\Documents\info.txt"))
        {
            if (line.Contains("title") && current == null)
                current = new List<string>();
            else if (line.Contains("info") && current != null)
            {
                groups.Add(current);
                current = null;
            }
            if (current != null)
            richTextBox1.Text = line;
        }
    }

The problem with this it reads the full line and the last entry is read

I hope someone can help me. Thanks in advance


Solution

  • Consider your data is in a file named data.txt.

    Logic: Read the data, split by new line, find lines containing "title =". Remove that identifier and take the rest of the line.

    string data = File.ReadAllText("data.txt");
    string identifier = "title =";
    
    List<string> results = 
        data.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
        .Where(x => x.Contains(identifier))
        .Select(x => x.Replace(identifier, String.Empty).Trim()).ToList();
    

    After that, you'll have list of strings in results. Do whatever you want with it.

    If you need to read it line by line like you tried, then:

    string identifier = "title =";
    string data = File.ReadAllText("data.txt");
    
    List<String> results = new List<string>();
    
    foreach(string line in File.ReadAllLines("data.txt"))
    {
        if(line.Contains(identifier))
        {
            results.Add(line.Replace(identifier, string.Empty).Trim());
        }
    }