我有一个字符串生成器,其中包含电子邮件ID(它包含数千个电子邮件ID)
StringBuilder sb = new StringBuilder();
foreach (DataRow dr2 in dtResult.Rows)
{
strtxt = dr2[strMailID].ToString()+";";
sb.Append(strtxt);
}
string filepathEmail = Server.MapPath("Email");
using (StreamWriter outfile = new StreamWriter(filepathEmail + "\\" + "Email.txt"))
{
outfile.Write(sb.ToString());
}
现在数据存储在文本文件中,如下所示:
abc@gmail.com; ab@gmail.com; abc@gmail.com; ab@gmail.com; abc@gmail.com; ab@gmail.com; abc@gmail.com; ab@gmail.com ; abc@gmail.com; ab@gmail.com; abc@gmail.com; ab@gmail.com; abc@gmail.com; ab@gmail.com; abc@gmail.com; ab@gmail.com; ABC @ gmail.com; ab@gmail.com; abc@gmail.com; ab@gmail.com; abc@gmail.com; ab@gmail.com; abc@gmail.com; ab@gmail.com; ABC @的Gmail .COM; ab@gmail.com; abc@gmail.com; ab@gmail.com; abc@gmail.com; ab@gmail.com; abc@gmail.com; ab@gmail.com; abc@gmail.com; ab@gmail.com;
但我需要存储它们,就像每行只应该只有10个电子邮件ID,这样我看起来不错**
任何想法如何在.txt文件中格式化这样的数据?任何帮助都会很棒
答案 0 :(得分:2)
只需在循环中添加一个计数器,每隔10行追加一个换行符。
int counter = 0;
StringBuilder sb = new StringBuilder();
foreach (DataRow dr2 in dtResult.Rows)
{
counter++;
strtxt = dr2[strMailID].ToString()+";";
sb.Append(strtxt);
if (counter % 10 == 0)
{
sb.Append(Environment.NewLine);
}
}
答案 1 :(得分:1)
使用计数器并在每个第十项中添加换行符:
StringBuilder sb = new StringBuilder();
int cnt = 0;
foreach (DataRow dr2 in dtResult.Rows) {
sb.Append(dr2[strMailID]).Append(';');
if (++cnt == 10) {
cnt = 0;
sb.AppendLine();
}
}
string filepathEmail = Path.Combine(Server.MapPath("Email"), "Email.txt");
File.WriteAllText(filepathEmail, sb.ToString());
注意:
StringBuilder
连接字符串,而不是先连接然后追加。Path.Combine
组合路径和文件名,这适用于任何平台。File.WriteAllText
方法将字符串保存在一次调用中,而不是写入StreamWriter
。答案 2 :(得分:0)
因为它说你可以添加一个“换行符”我建议在每个地址后添加'\ t'标签,这样你的文件将是CSV格式,你可以在Excel中导入它。
答案 3 :(得分:0)
使用计数器跟踪已写入的邮件数量,如下所示:
int i = 0;
foreach (string mail in mails) {
var strtxt = mail + ";";
sb.Append(strtxt);
i++;
if (i % 10==0)
sb.AppendLine();
}
每写10封邮件,我模10等于0,所以你在字符串生成器中放置一个结束行。 希望这可以提供帮助。
答案 4 :(得分:0)
如果你不介意任何开销,这是使用LINQ的另一种方法。
string filepathEmail = Server.MapPath("Email");
using (StreamWriter outfile = new StreamWriter(filepathEmail + "\\" + "Email.txt"))
{
var rows = dtResult.Rows.Cast<DataRow>(); //make the rows enumerable
var lines = from ivp in rows.Select((dr2, i) => new {i, dr2})
group ivp.dr2[strMailID] by ivp.i / 10 into line //group every 10 emails
select String.Join(";", line); //put them into a string
foreach (string line in lines)
outfile.WriteLine(line);
}