简体   繁体   English

C#将文本添加到现有文本文件

[英]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. 我一直在阅读如何使用.split('symbol')所以也许可以。

For example: user123123.txt, My name is {namebox}. 例如:user123123.txt,我的名字是{namebox}。 I am {agebox} years old. 我{agebox}岁。 namebox = Amy agebox = 21 namebox = Amy agebox = 21 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. 我试过使用string.format()函数,但无法弄清楚如何读取文本文件并将值插入我需要的位置。

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.Replace几次。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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