簡體   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