[英]Weird Array issue
所以我正在編寫一個 C# 控制台應用程序。 我有一個要發送到數據庫的文本文件。 計划是有多個文本文件,只有一個插入。 go 對於第一行來說一切似乎都很好。 一旦我到達第二行,數組認為它的長度只有 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
你只需要
string[] words = line.Split('\t');
然后你必須驗證內容和你的操作是否匹配,一個粗略的想法:
System.Diagnostics.Trace.Assert (words.Count == 9);
使用上面的代碼,我創建了一個簡單的 output 文件步驟,它符合您的預期結構,並且您的代碼確實正確地解析了文件。 您的問題似乎是基於數據
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);
拆分的 tabs 參數只需要一個制表符。 您正在告訴它所有可能的拆分值。 如所寫,您是在告訴它在選項卡或選項卡等上拆分。
第二行的格式可能不正確。
您可以從導入文件中發送幾行的副本嗎?
我真的不明白為什么需要在 split 方法中指定所有這些制表符。
只需執行以下操作:
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.