StreamReader获取某些字符之间的字符串

时间:2014-01-03 23:07:13

标签: c# c#-4.0 arraylist streamreader

我有一个程序通过Web服务使用模板发送电子邮件。为了测试模板,我做了一个简单的程序来读取模板,用虚拟值填充它并发送它。问题是模板具有不同的“填充”变量名称。所以我想要做的是打开模板,列出变量,然后用虚拟文本填充它们。

对不,我有类似的东西:

StreamReader SR = new StreamReader(myPath);
.... //Email code here
Msg.Body = SR.ReadToEnd();
SR.Close();

Msg.Body = Msg.Body.Replace(%myFillInVariable%, "Test String");
....

所以我想,打开模板,在“%”之间搜索值并将它们放在ArrayList中,然后执行Msg.Body = SR.ReadToEnd();部分。循环ArrayList并使用Array的值执行Replace部分。

我找不到的是如何读取%标签之间的值。关于使用何种方法的任何建议将不胜感激。

谢谢,

更多细节:

很抱歉,如果我不清楚的话。我从下拉列表中将TEMPLATE的名称传递给脚本。我可能有几十个模板,它们都有不同的%VariableToBeReplace%。这就是为什么我想用StreamReader读取模板,找到所有%值名称%,将它们放入一个数组然后填充它们 - 我已经知道该怎么做了。它在代码中得到了我需要替换的名称,我不知道该怎么做。

2 个答案:

答案 0 :(得分:2)

我不确定你的问题,但这里有一个如何进行替换的样本。

您可以在LinqPad中运行和播放此示例。

将此内容复制到文件中,并将路径更改为所需内容。含量:

Hello %FirstName% %LastName%,

We would like to welcome you and your family to our program at the low cost of   %currentprice%. We are glad to offer you this %Service%

Thanks,
Some Person

代码:

var content = string.Empty;
using(var streamReader = new StreamReader(@"C:\EmailTemplate.txt"))
{
    content = streamReader.ReadToEnd();
}

var matches = Regex.Matches(content, @"%(.*?)%", RegexOptions.ExplicitCapture);

var extractedReplacementVariables = new List<string>(matches.Count);
foreach(Match match in matches)
{
    extractedReplacementVariables.Add(match.Value);
}

extractedReplacementVariables.Dump("Extracted KeyReplacements");

//Do your code here to populate these, this part is just to show it still works
//Modify to meet your needs
var replacementsWithValues = new Dictionary<string, string>(extractedReplacementVariables.Count);
for(var i = 0; i < extractedReplacementVariables.Count; i++)
{
    replacementsWithValues.Add(extractedReplacementVariables[i], "TestValue" + i);
}

content.Dump("Template before Variable Replacement");

foreach(var key in replacementsWithValues.Keys)
{
    content = content.Replace(key, replacementsWithValues[key]);
}

content.Dump("Template After Variable Replacement");

LinqPad的结果: LinqPad Results

答案 1 :(得分:0)

我不确定我是否理解了您的问题但是,您可以尝试在模板的第一行填写变量&#39;。

类似的东西:

StreamReader SR = new StreamReader(myPath);
String fill_in_var=SR.ReadLine();
String line;
while((line = SR.ReadLine()) != null)
{
    Msg.Body+=line;
}
SR.Close();

Msg.Body = Msg.Body.Replace(fill_in_var, "Test String");