从项目目录中读取文本文件内容,并将参数传递给文本

时间:2019-06-27 07:51:09

标签: c# string

我正在从项目目录中读取文本文件。

string FilePath = Path.Combine(Path.Combine(
   AppDomain.CurrentDomain.BaseDirectory), 
 @"Template\MailContent.txt");

string FileText = File.ReadAllText(FilePath);

文本文件内容(具有多个动态参数)将类似于 FileText 变量中的内容。

Hey {UserName}, Congratulations ! you have {Result} this exam.

,我有UserName的数据,而Result将是动态的。喜欢,

string UserName = "Brijesh";
string Result = "Passed";

所以,结果应该是

string FinalText = Hey Brijesh, Congratulations ! you have Passed this exam.

2 个答案:

答案 0 :(得分:2)

这应该做到:

string FilePath = Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory), @"Template\MailContent.txt");
string FileText = File.ReadAllText(FilePath);
string UserName = "Brijesh";
string Result = "Passed";

 var replacements = new ListDictionary{ {"{UserName}", UserName }, {"{Result}", Result }}

foreach (DictionaryEntry replacement in replacements)
    {
        FileText = FileText.Replace($"{replacement.Key}", $"{replacement.Value}");
    }

答案 1 :(得分:2)

让我们将所有替换内容组织到集合中,例如Dictionary<string, object>

Dictionary<string, object> replace = new Dictionary<string, object>() {
  {"UserName", "Brijesh"},
  {"Result", "Passed"},
  {"Score", 85},
  {"Grade", "B+"},
  //TODO: Add more parameters here 
}; 

然后我建议使用正则表达式来匹配{Word}模式并替换为其值:

using System.Text.RegularExpressions;

...

string FileText = 
  "Hey {UserName}, Congratulations ! you have {Result} this exam. Your score is {Score}.";

string result = Regex.Replace(FileText, 
   "{[A-Za-z]+}", 
    match => replace.TryGetValue(match.Value.Trim('{', '}'), out var value) 
      ?  value?.ToString()
      : "{???}");           // when we don't have a value

Console.Write(result); 

结果:

Hey Brijesh, Congratulations ! you have Passed this exam. Your score is 85.