奇怪的数组问题

问题描述:

所以我写了一个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

使用上面的代码,我创建了一个简单的输出文件步骤,它符合您的预期结构,并且您的代码可以正确解析文件。你的问题似乎是基于数据

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

您只需要

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

的标签参数拆分只需要有一个制表符。你正在告诉它所有可能的值。正如所写的,你告诉它要在选项卡或选项卡上分割,等等。

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

你可以从导入文件发送几行文本的副本吗?

+0

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

我真的不明白为什么你需要指定在拆分方法中的所有这些制表符。

就做这样的事情:

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 
}