C# How to read and cache text file data?

Hi, I’m new to using System.IO and I want to ask how could I get data from a text file and
get find the serverName and serverIp per each server. When players joins a server, it saves the serverName and serverIp to this file like the format below.

... //The file can expand more depending on the servers the players has visited.

And I want to get the serverName and serverIp after it has written it.
How can I get the string after [serverName] from the text file?
How can I get the string after [serverIp] from the text file?
How can I get how many servers are listed in the file? So I could use those data to draw GUIs to list the history to servers visited. I’ve been stressed with this issue, I’ve searched few of the C# System.IO for help but I couldn’t really get what i want. If you could write the code and comment details on it it would be great, Thanks in advance.

below is a more complicated way of doing it and yes, you could do this a bunch of different ways, you could use string.Split and split on the ending square bracket, returning kind of a key value pair. the example below will get you there.

using System.Collections.Generic;
using System.IO;

//...normal stuff

List<string> fileLines = new List<string>(File.ReadLines("somepathtothefile"));
string serverName = string.Empty;

foreach(string line in fileLines) {
  if (line.Contains("[serverName]")) {
    var lastEndingBracket = line.LastIndexOf("]");
    serverName = line.SubString(lastEndingBracket + 1, line.Length);

// ... other crap

We create a List of string, read each line from the file and add it as an item/entry in the List.

We create an empty serverName string for the server name, you can similar for the ip. using null or string.empty allows you to do conditions using string.IsNullOrEmpty for example.

We then iterate over each line in the List of string(or the list of lines from the file), we check to see if the line contains(could use StartsWith) the value [serverName], if it doesn’t, we move on. If it does we get the index(zero based from the left first character in that string(0) to the last closing square bracket(1)) of the last square bracket on the line(in the string) and pump it into a int var(we can infer the type value due to LastIndexOf returning an int type).

We then set serverName to the serverName, we are using SubString to begin the hacking of the string plus one(to move to the next character) all the way to the end of the string(the length). At this point you could break from the foreach look or continue if you also were looking for the ip address.