2010-08-05 66 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); 
}