2011-06-02 79 views
1

所以我寫了一個C#控制檯應用程序。我有一個我想發送到數據庫的文本文件。該計劃是有多個文本文件和只有一個插入。第一行似乎一切正常。有一次,我到2號線的排列認爲它只有2。奇怪的數組問題

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace UKImporter 
{ 
class Program 
{ 
    static void Main(string[] args) 
    { 
     string[] lines = System.IO.File.ReadAllLines(@"C:\out\output.txt"); 
     System.Console.WriteLine("Contents of writeLines2.txt =:"); 

     foreach (string line in lines) 
     { 
      string sellername, sku, date1, quantity1, date2, asin, date3, date4, FNSKU; 
      char[] tabs = { '\t', '\t', '\t', '\t', '\t', '\t', '\t', '\t', }; 
      string[] words = line.Split(tabs); 
      sellername = words[0]; 
      sku = words[1]; 
      date1 = words[2]; 
      quantity1 = words[3]; 
      date2 = words[4]; 
      asin = words[5]; 
      date3 = words[6]; 
      date4 = words[7]; 
      FNSKU = words[8]; 
      Console.WriteLine("\t" + line); 
      UKDataBLL u = new UKDataBLL(); 
      //u.AddToDatabase(sku, DateTime.Now, Convert.ToInt16(quantity1), DateTime.Now, asin, DateTime.Now, DateTime.Now, FNSKU); 

      foreach (string s in words) 
      { 
       System.Console.WriteLine(s); 
      } 

     } 

     // Keep the console window open in debug mode. 
     Console.WriteLine("Press any key to exit."); 
     System.Console.ReadKey(); 

    } 
} 
} 

編輯這裏的長度是文件

A2LQ9QFN82X636 ACD_fivecrowns 6/1/11 5:30 0 6/1/11 5:30 B00000IV35 6/1/11 5:30 6/1/11 5:30 X0000PGTT9

A2LQ9QFN82X63 ACD_caylus_magna_carta 6/1/11 5:30 0 6/1/11 5:30 B000N3SOUM 6/1/11 5:30 6/1/11 5:30 X0000PGM23

A2LQ9QFN82X63 AMX_JrSpaceHelmet-LBL 6/1/11 5:30 0 6/1/11 5:30 B0008F6WMM 6/1/11 5:30 6/1/11 5:30 X0000PQBUL

的一些文字
+0

張貼文件 – BlackBear 2011-06-02 17:29:14

+0

愚蠢的問題的內容,但你知道第二行有標籤,是嗎?以二進制模式打開文件將驗證該行(應該看11/0B)在該行上列出 – billinkc 2011-06-02 17:29:40

+0

您指的是線陣列? – razlebe 2011-06-02 17:30:21

回答

2

使用上面的代碼,我創建了一個簡單的輸出文件步驟,它符合您的預期結構,並且您的代碼可以正確解析文件。你的問題似乎是基於數據

string[] content = new string[] { "a\tb\tc\td\te\tf\tg\th\ti", "a\tb\tc\td\te\tf\tg\th\ti" }; 
    System.IO.File.WriteAllLines(@"C:\sandbox\output.txt", content); 
+0

我很困惑@billinkc爲什麼我會嘗試輸出我正在閱讀的內容? – 2011-06-02 17:48:29

+0

我只是提供生成預期文件格式的代碼。運行驗證您的主邏輯是正確的。相反,它是文件中不符合模板格式的數據。 – billinkc 2011-06-02 18:01:05

3

您只需要

string[] words = line.Split('\t'); 

然後你需要驗證的內容和你的操作搭配,粗的想法:

System.Diagnostics.Trace.Assert (words.Count == 9); 
+0

我相信你的意思words.Length == 9,我試過了,它通過第二次給出錯誤。 – 2011-06-02 17:43:15

+0

你的調試器告訴你什麼? – 2011-06-02 17:53:37

+0

聲明失敗 – 2011-06-02 17:58:10

1

的標籤參數拆分只需要有一個製表符。你正在告訴它所有可能的值。正如所寫的,你告訴它要在選項卡或選項卡上分割,等等。

有可能第二行的格式不正確。

你可以從導入文件發送幾行文本的副本嗎?

+0

立即檢查原來的文章 – 2011-06-02 17:48:55

1

我真的不明白爲什麼你需要指定在拆分方法中的所有這些製表符。

就做這樣的事情:

foreach (string line in lines) 
{ 
    string[] columns= line.Split('\t'); 
    if (columns.Length != 9) // Or how many colums the file should have. 
     continue; // Line probably not valid 

    // Now access all the columns of the line by using 
    // columns[0], columns[1], etc 
}