Search code examples
c#listchattextwriter

Advanced Chat Program (Writing Prefixes)


I've coded a Chat Program giant and so far have managed to get over every obstacle that has stopped me, even the ones I have thought over for days, but this one I can't get my head around. So I'm working on a prefix system, I type the target name into the target textbox and a prefix name into the prefix textbox then click prefix button. I have made it to write the username and chosen prefix to a text file with a "|" seperating it. Like this:

void writePrefixes(string target, string prefixs)
    {
        TextWriter twp = new StreamWriter("prefix.txt");
        twp.WriteLine(target + "|" + prefixs + Environment.NewLine);
        twp.Close();
    }

Now, everytime the server starts up, it imports the textfile and uses a foreach loop to load each one into a List. Now, everytime a client sends a message, I want it's username to be checked with "target" in the list, then it's username modified to have the prefix before it. How can I do this? Thanks in advance! Sorry about the long question, I am new, if it's too long, tell me!


Solution

  • So you have a textfile that has data like this:

    user1|pre1
    user2|pre2
    etc.

    And you are loading those strings into a plain List? I think something like this would be the best option:

    var userList = new List<string>();
    userList.Add("TestUser1|pre1");
    userList.Add("TestUser2|pre2");
    
    foreach (var user in userList)
    {
        var userParts = user.Split(new[] { '|' });
        var userName = userParts[0];
        var prefix = userParts[1];
    
        Console.WriteLine(string.Format("{0}{1}", prefix, userName));
    }
    

    Hope I have understood you correctly.