Advanced Chat Program (Writing Prefixes)

388 views Asked by At

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!

2

There are 2 answers

1
Bojan Spasevski On BEST ANSWER

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.

1
DerApe On

So you basically have two lists: one with usernames, one with prefixes, both strings. I guess you would have to store every prefix entered, seperated by a char not used by your prefix.

//go through file
var entry = file.ReadLine().Split('|');
userList.Add(entry[0]);
prefixList.Add(entry[1]);

//when you want to go for the prefix
var idx = userList.IndexOf(username);
var allPrefix = prefixList[idx].Split("seperator");
var newPrefix = allPrefix[prefixList[idx].Count - 2];

//yes you have to make sure the index is correct, you dont leave bounderies etc. but I hope you get the idea

You also would have to make sure the index which was used before is removed from the list to be saved.