Reputation: 209
I currently have a text file that has a couple of sentences that looks like this:
Hello. Your name is <name> and the username you have chosen is <username>.
Your password is <password>. Your friend's username is <username>
and their password is <password>.
What I first do is ask the user the following questions:
public string questions(string sentences)
{
Console.Write("Enter Your Name: ");
string name = Console.ReadLine();
Console.Write("Enter Your Username: ");
string userName= Console.ReadLine();
Console.Write("Enter Your Password: ");
string password= Console.ReadLine();
string textFile = File.ReadAllText(sentences);
textFile = textFile.Replace("<name>", name);
textFile = textFile.Replace("<username>", userName);
textFile = textFile.Replace("<password>", password);
File.WriteAllText(sentences, textFile);
return textFile;
}
When the user inputs their name, it's not a problem because there is only one <name>
, however, when it comes to the password and username, it's a problem. For example, when the user inputs the username, it replaces everything in the file that says <username>
when I only want to replace the first <username>
. What I would like this program to do is to read the file and every time it encounters <name>
, <password>
, or <username>
to prompt the user to enter their name, password or username and replace only that placeholder, not all the placeholders with similar names.
Is there a way I can edit my current code to achieve this? I thought about numbering stuff in the text file like <name1>
or <username1>
but then this would only work with this particular text file. What if the text file contains an unknown amount of usernames or passwords?
Upvotes: 0
Views: 217
Reputation: 3744
you can try Regex.Replace
var regex = new Regex("<username>");
textFile = regex.Replace(textFile, userName, 1);
Upvotes: 2