2010-08-05 67 views
2

IHAVE一个字符串生成器,它conatins电子邮件ID(它conatins成千上万的电子邮件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()); 
} 

现在数据越来越存储在文本文件中这样的格式化数据:

[email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; ABC @ gmail.com; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; ABC @的Gmail。 COM; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected];

,但我需要把它们存储等,其中的每一行应该只仅10个电子邮件ID,这样我看起来不错**

任何想法如何在.txt文件中的数据格式是这样?任何帮助将是伟大的

回答

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

使用计数器,并添加一行突破每十个项目:

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 Concatentate字符串,而不是先串接,然后追加。
  • 使用Path.Combine来组合路径和文件名,这可以在任何平台上运行。
  • 您可以使用File.WriteAllText方法在一次调用中保存字符串,而不是写入StreamWriter
0

因为它说你可能会添加一个“换行符”我建议在每个地址之后添加'\ t'选项卡,因此你的文件将是CSV格式,你可以在Excel中导入它。

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,所以你杜绝行字符串生成器。 希望这可以帮助。

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); 
}