繁体   English   中英

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

[英]C# Add text to existing text file

在我的申请中,我有一个注册表格。 当他们提交表单时,我希望它从这些文本框中获取值并将它们合并到文本文档的证书部分中。 因此,代码需要读取文本文件,将数据插入正确的位置,然后另存为新文件。 我一直在阅读如何使用.split('symbol')所以也许可以。

例如:user123123.txt,我的名字是{namebox}。 我{agebox}岁。 namebox = Amy agebox = 21 namebox = Amy agebox = 21

我真的不知道该怎么做。 我试过使用string.format()函数,但无法弄清楚如何读取文本文件并将值插入我需要的位置。

就像是:

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

只需使用string.Replace几次。

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

该逻辑可以如下实现:

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

客户代码:

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