2012-08-07 52 views
0

我有一個小問題導入到數據庫的TXT文件。 該文件的結構有點困難。 在第一行是隻喜歡描述:TXT文件 - 拆分不同的內容與C#

  • 典型虛擬
  • 狀態就緒
  • 3號 等。

的描述(20個22行之間)之後而來的表所示:

PartStatus Result Measurement1  Measurement2  ..... 
900   OK  0     20    ..... 
600   Passed 30    400    ..... 

我不知道,在這行的表開始。 讀取和處理文件以將其寫入數據庫的最佳方式是什麼?

目前我使用StreamReader並將每個字符串添加到數據表中。

問候

阿明

SampleFile: TestFile

+0

你能給我們一個CSV的樣本嗎? – 2012-08-07 07:42:33

+0

有一個示例文件可以讓你更容易回答。你能分享一個嗎? – danish 2012-08-07 07:47:59

+0

什麼是上傳文件的最佳方式? – NimraF 2012-08-07 08:02:54

回答

1

試試這個:File Helpers。過去我曾經涉獵過它,可能會簡化閱讀CSV的過程。

1

您可以使用TextFiledParser類,只是跳過無效的行。

using (var reader = new TextFieldParser(@"c:\YourFile")) 
{ 
    reader.TextFieldType = FieldType.Delimited; 
    reader.Delimiters = new string[] {","}; 
    string[] currentRow = null; 
    while (!reader.EndOfData) 
    { 
     try 
     { 
      currentRow = reader.ReadFields(); 
      // do something with the values 
     } 
     catch (MalformedLineException ex) 
     { 
      // skip invalid lines and handle it 
     } 
    } 
} 
1

在Codeplex的CommonLibrary.NET項目中也有專門的CSV解析支持。您可以使用此庫找到一個CSV解析示例here

UPDATE

下面是一些代碼,可用於解析類似於你有上面的一個文本,並使用CommonLibrary.NET。請注意,原始文本被首先降低在表頭(origText.Substring(origText.IndexOf("PartStatus")))開始,和正則表達式匹配是用來與單個逗號(Regex.Replace(sometext, "[ ]+", ","))取代一個或多個連續的空格字符:

var origText = 
    "Type Dummy\n" + 
    "Status Ready\n" + 
    "# Comment line\n" + 
    "# Another comment line\n" + 
    "PartStatus Result Measurement1  Measurement2\n" + 
    "900   OK  0     20\n" + 
    "600   Passed 30    400\n"; 

var trimmedText = 
    Regex.Replace(origText.Substring(origText.IndexOf("PartStatus")), 
        "[ ]+", ","); 

var csvDoc = Csv.LoadText(trimmedText, true, false, ","); 

Console.WriteLine(csvDoc.Get<int>(1, "Measurement2")); 
Console.WriteLine(csvDoc.Get<string>(0, "Result")); 

將產生輸出:

400 
OK 

CommonLibrary.NET的CSV解析組件還提供了一種簡單的方式來將CSV數據變換成一個ADO.NETDataTable

var table = csvDoc.ToDataTable(); 
+1

+1非常合理的答案,一個很好的例子 – 2012-08-07 18:14:25