2012-07-24 39 views
0

我有一個任務,我需要讀取文本文件,然後將每行分解成列,然後我需要將其插入到數據庫中。讀取文本文件,然後將行分解成列

這是最好的方法是什麼?任何幫助將不勝感激,如果你可以提供代碼會更好。

這是我迄今爲止

string filename = Server.MapPath("~/Text_File_4.txt"); 

    StreamReader sr = new StreamReader(filename); 

    string styl; 
    string colr; 
    string sdim; 
    string size; 
    string qty; 
    string line; 

    string sprice; 
    string sretail; 

    while ((line = sr.ReadLine()) != null) 

    { 
     styl = line.Substring(0, 6); 
     colr = line.Substring(6, 2); 
     sdim = line.Substring(8, 1); 
     size = line.Substring(14, 3); 
     qty = line.Substring(19, 5); 


     sprice = line.Substring(27, 6); 
     sretail = line.Substring(38, 4); 

     con.Open(); 
     cmd = new SqlCommand("insert into ststyl00(ststyl, stcolr, stsdim, stszcd, stprq, strprq) values(@ststyl, @stcolr, @stsdim, @stszcd, @stprq, @strprq)", con); 

     cmd.Parameters.Add("@ststyl", SqlDbType.VarChar, 15).Value = styl; 
     cmd.Parameters.Add("@stcolr", SqlDbType.VarChar, 3).Value = colr; 
     cmd.Parameters.Add("@stsdim", SqlDbType.VarChar, 8).Value = sdim; 
     cmd.Parameters.Add("@stszcd", SqlDbType.VarChar, 3).Value = size; 

     cmd.Parameters.Add("@stprq", SqlDbType.VarChar, 8).Value = sprice; 
     cmd.Parameters.Add("@strprq", SqlDbType.VarChar, 8).Value = sretail; 
     cmd.ExecuteNonQuery(); 
     con.Close(); 



    } 
+0

到目前爲止你有什麼 – 2012-07-24 03:23:35

+1

列寬是固定的嗎? CSV? – 2012-07-24 03:23:39

回答

3

輸入是一個CSV

如果輸入文件是CSV文件,我強烈建議您使用現有的CSV Reader類在

http://www.codeproject.com/Articles/9258/A-Fast-CSV-Reader

輸入固定寬度

如果您的輸入是固定寬度,j ust讀取所有行,並將每行分解成適當的結構以存儲在數據庫中(稍後詳細介紹)。

如果你有一點點文本閱讀(也許幾兆字節或更少),只要使用

File.ReadAllLines 

http://msdn.microsoft.com/en-us/library/s2tte0y1

中的所有文件的行讀入一個串[]

寫入到數據庫

您現在有讀取文件的能力。現在,您需要將它寫出到數據庫中。據推測,有一個數據庫表與給定的模式匹配的文件中的數據。查看ADO.Net以瞭解如何寫入數據庫並根據需要提出具體問題。

http://msdn.microsoft.com/en-us/library/h43ks021(v=vs.100).aspx

0

這聽起來像你必須有分隔符的文本文件。將數據分隔成列的分隔符,例如

數據1,數據2,數據3,數據4

分隔符可以是逗號或不出現成常規數據的任何其它字符。如果您使用這種格式的文本文件,則可以輕鬆解析並將其推送到數據庫。

該方法可能是 - 您使用StreamReader打開文件。逐行讀取文件,即一次讀取一行。通過指定分隔符將行分割成列。

string[] lineData = sr.ReadLine().split('delimiter'); 
foreach(string colData in lineData) 
{ 
    //store data into appropriate collections and push it to database 
} 
0

除了其他解析技術已經建議,你可以結合使用TextFieldParser類(它在Microsoft.VisualBasic.FileIO命名空間)你已經寫

的ADO.Net代碼
相關問題