简体   繁体   中英

C# Add text to existing text file

In my application I have a sign up form. When they submit the form I would like it to take the values from these these textboxes and merge them into certian parts of a text document. So the code needs to read the textfile, insert the data in the right spots and then save as a new file. I have been reading on how to use the .split('symbol') so maybe that would work.

For example: user123123.txt, My name is {namebox}. I am {agebox} years old. namebox = Amy agebox = 21

I really have no idea how to do this. I have tried using the string.format() function but can't figure out how to have it read the text file and insert the values where I need them.

Something like:

// giving name = "Marvin", age = "23"
var name = "Marvin"; 
var age = 23;

var text = File.ReadAllText("c:\\path\\to\\file");
var result = text.Replace("{name}", name).Replace("{age}", age);
File.WriteAllText("c:\\path\\to\\anotherFile", result);

Just use string.Replace a couple of times.

string newString = "My name is {namebox}. I am {agebox}"
                   .Replace("{namebox}", txtName.Text)
                   .Replace("{agebox}", txtAgeBox.Text);

This logic could be implemented as follows:

public static string CustomFormat(string format, Dictionary<string, string> data)
{
    foreach (var kvp in data)
    {
        string pattern = string.Format("{{{0}}}", kvp.Key);
        format = format.Replace(pattern, kvp.Value);
    }
    return format;
}

Client code:

const string format = "My name is {namebox}. I am {agebox} years old.";
var input = new Dictionary<string, string>
    {
        { "namebox", "Jon Doe" },
        { "agebox", "21" }
    };
string s = CustomFormat(format, input);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM