2013-01-07 21 views
0

這是我需要在路徑中定義文件路徑的代碼。在「字符串路徑」中,我有類似這樣的內容。如何完成循環並導入文本文件

(C:\文件夾\的text.txt)

string path = @"C:\path.txt"; 
StreamReader str = new StreamReader(path); 
string datasample; 

while ((datasample = str.ReadLine()) != null) 
     { 
     } 

什麼,我需要做的是導入txt文件到SQL table.here是我的導入工作正常代碼。

StreamReader sr = new StreamReader(Global_Variables.filename.ToString()); 
      DataTable dt = new DataTable(); 
       DataRow row; 
       dt.Columns.Add(new DataColumn("Reports")); 

       while (!sr.EndOfStream) 
       { 
        string value = sr.ReadLine(); 
        if ((value.Length != 0) && (value != "")) 
        { 
         row = dt.NewRow(); 
         row[0] = value; 
         dt.Rows.Add(row); 
        } 
       } 
       SqlBulkCopy bc = new SqlBulkCopy(Global_Variables.con.ConnectionString, SqlBulkCopyOptions.TableLock); 
       bc.DestinationTableName = "tbl_WinApps_ApprovedExpReports"; 
       bc.BatchSize = dt.Rows.Count; 
       Global_Variables.con.Open(); 
       bc.WriteToServer(dt); 
       bc.BulkCopyTimeout = 120; 
       bc.Close(); 
       Global_Variables.con.Close(); 

我似乎無法加入兩個代碼together.pls幫助:(

+0

您是否嘗試過string path = @「C:\ path.txt」; StreamReader sr = new StreamReader(path);而不是第二個腳本中的第一行? – twoleggedhorse

+0

不行不行 – user1954418

回答

0

好像你已經遍歷文件中使用StreamReader的,所以你可以做這樣的事情:

string path = File.ReadAllText(@"C:\path.txt"); 
string line = ""; 
StreamReader sr = new StreamReader(path); 
DataTable dt = new DataTable(); 
DataRow row; 
dt.Columns.Add(new DataColumn("Reports")); 

while ((line = sr.readLine()) != null) 
{ 
    if ((line.Length != 0) && (line != "")) 
    { 
     row = dt.NewRow(); 
     row[0] = line; 
     dt.Rows.Add(row); 
    } 
} 

SqlBulkCopy bc = new SqlBulkCopy(Global_Variables.con.ConnectionString, SqlBulkCopyOptions.TableLock); 
bc.DestinationTableName = "tbl_WinApps_ApprovedExpReports"; 
bc.BatchSize = dt.Rows.Count; 
Global_Variables.con.Open(); 
bc.WriteToServer(dt); 
bc.BulkCopyTimeout = 120; 
bc.Close(); 
Global_Variables.con.Close(); 
+0

我已經這樣做了,那就是它只循環一次,添加新行不會直到文件結束。只有1行被導入到SQL – user1954418

+0

我已經編輯了代碼,現在能工作嗎? –

+0

它仍然沒有..我想要的是找到並處理文本文件INSIDE我的字符串路徑..什麼是寫在「C:\ path.txt」 – user1954418