2017-01-30 56 views
-1

這裏保存的數據表值表: enter image description here在.txt文件C#

我想獲取該表的所有列和行,並保存在一個.txt文件。

文本文件名必須是SubscriberID.txt(例如:281063.txt或281064.txt)並保存在文件夾名稱manoj中。

在281063.txt文件中,數據保存在SubscriberID中:60; npercentscore:60; nevaleid:7091,courseID:1,... 就像這樣。

Here i take all the data to a datatable: 
string query = "SELECT * FROM DATAFETCH"; 
     SqlCommand cmd = new SqlCommand(query, conn); 

     DataTable dt = new DataTable(); 
     dt.Load(cmd.ExecuteReader()); 

我該如何使用c#asp.net實現我的目標? 有什麼建議?

+1

的可能的複製[導出一個C#的DataSet一個文本文件](http://stackoverflow.com/questions/7174077/export-ac-sharp-dataset-to-a-text-file) –

+0

先生我想根據SubscriberID的名稱保存在文件夾中的文件。 txt –

回答

0

如果你需要每行一個文件,你可以像這樣做:

 foreach (DataRow dr in dt.Rows) 
     { 
      StreamWriter sw = new StreamWriter(PathToStoreTheFile + dr["SubscriberID"].ToString() + ".txt"); //create the file 
      string line = "SubscriberID:" + dr["SubscriberID"].ToString() + ";"; 
      line += "npercentscore:" + dr["npercentscore"].ToString() + ";"; 
      line += "nevaleid:" + dr["nevaleid"].ToString() + ";"; 
      line += "courseID:" + dr["courseID"].ToString() + ";"; 
      //and so on 
      sw.WriteLine(line); //write data 
      sw.Close(); 
     } 

或者你也可以通過列迭代:

 foreach (DataRow dr in dt.Rows) 
     { 
      StreamWriter sw = new StreamWriter(PathToStoreTheFile + dr["SubscriberID"].ToString() + ".txt"); 
      string line = ""; 

      foreach (DataColumn dc in dt.Columns) 
      { 
       line += dc.ColumnName + ":" + dr[dc].ToString() + ";"; 
      } 
      sw.WriteLine(line); 
      sw.Close(); 
     } 
+0

是的,我想每行1個文件...和文件名必須是SubscriberID.txt ..你可以建議我? –

+0

Here is ... – Wudge

+0

訪問路徑'C:\ Program Files(x86)\ IIS Express \ 281063.txt'在StreamWriter中被拒絕。錯誤 –