是否从RichTextBox中的每一行获取文本



我想从RichTextBox中的每一行中提取一个文本,并在该文本行的开头和结尾添加一个常量文本。当我按下按钮时,新文本将被导出/保存到文本文件中。我可以创建一个循环,但如何在开始和结束处添加条件?

private void button1_Click(object sender, EventArgs e)
{   
string text1 = "hello";
string text2 = richboxtext.Text;
string text3 = "goodbye";
for (int i = 0; i < text2.Length; i++)
{
if(...)
{
...
}
}
File.WriteAllText(@"C:Tempexapmle.txt", text);
}

只需在Lines字符串数组上循环:

string textb = "hello";            
string texte = "goodbye";
var sb = new StringBuilder();
foreach(var line in richTextBox1.Lines)
{
sb.AppendLine(textb + line + texte);
}
File.WriteAllText(@"C:Tempexapmle.txt", sb.ToString());

我想在您的帮助下分享我开发的代码的最终版本。

有了这段代码,我开发了一个脚本,将每一行的IP地址批量添加到Fortinet中。我开发了一个脚本,将相同的IP地址集体分配给一个组。

private void button1_Click(object sender, EventArgs e)
{
string conf1 = "# config firewall address"; 
string code1 = "    edit " ;
string code2 = Environment.NewLine + "        set subnet ";
string code3 = "/32";
string code4 = Environment.NewLine + "    next" ;
string conf2 = "end";
string conf3 = "# config firewall addrgrp";
string code5 = Environment.NewLine + "    edit test-grp";
string code6 = Environment.NewLine + "        set member ";
string code7 = Environment.NewLine + "    next";
string conf4 = "end";
var ipadress = new StringBuilder();
foreach (var line in adresler.Lines)
{
ipadress.AppendLine(code1 + line + code2 + line + code3 + code4);
}
var ipgroup = new StringBuilder();
foreach (var line in adresler.Lines)
{
ipgroup.Append(line + " ");
}
File.WriteAllText(@"C:Tempexapmle.txt", conf1 + Environment.NewLine + ipadress.ToString() + Environment.NewLine + conf2);
File.WriteAllText(@"C:Tempexapmle2.txt", conf3 + code5 + code6 + ipgroup.ToString() + code7 + Environment.NewLine + conf4);
}

最新更新