2016-04-04 12 views
3

私はn個の行を含み、各行には1つの区切り文字を持つn個の列があります。テキストファイルの読み込みと列数のチェックはすべて同じです。

txtファイルを1行ずつ読み込み、すべての行をチェックする方法は同じです。いずれかの行に余分の列がある場合は、テキストとともに行番号を表示します。

は、私は私のtxtファイル内の行

147789-00,67、KB08,2007,12,0.000、0.000、0.000

A22951,67、RN3W、2007,12の下にあるとし0.000、0.000、0.000

946106-00,67、RN1W、2007,12,0.000、0.000、0.000,000

A22951,67、RN3W、2007,12,0.000、0.000、0.000

3行目に余分な列があり、同じ方法で1行に余分な列がある可能性があります。私が見つけたい余分な列。または、行に余分な区切り文字がある場合は、行番号をテキストとともに表示します。

foreach (string line in File.ReadLines(@"c:\file.txt", Encoding.UTF8)) 
{ 
     // how to match the columns  
} 

私は正しい道を進んでいます。誰か助けてください。

+0

余分な列はどういう意味ですか? n + 1個の列などがある?私たちの理解を助けるためにいくつかのサンプルデータを共有してください。 –

+0

更新された質問を確認してください – Rocky

+0

CSVHelper - > https://www.nuget.org/packages/CsvHelper/をご覧になることをお勧めします。彼らはyourserlfによって行う必要のない多くの基本機能を持っています –

答えて

1

char delimiter = ','; 
    int columnCount = -1; // or put the number if it's known 

    var errors = File 
    .ReadLines(@"c:\file.txt", Encoding.UTF8) // UTF-8 is default and can be skipped 
    .Select((line, index) => { 
     int count = line.Split(delimiter).Length; 

     if (columnCount < 0) 
     columnCount = count; 

     return new { 
     line = line, 
     count = count, 
     index = index 
     }; 
    }) 
    .Where(chunk => chunk.count != columnCount) 
    .Select(chunk => String.Format("Line #{0} \"{1}\" has {2} items when {3} expected", 
     chunk.index + 1, chunk.line, chunk.count, columnCount)); 

// To check if file has any wrong lines: 
if (errors.Any()) { 
    ... 
} 

// To print out a report on wrong lines 
Console.Write(String.Join(Envrironment.NewLine, errors)); 
次を使用することができ、無効な行を収集するには
+0

行が0から数えるときにエラーメッセージが表示されますエンドユーザは何かからカウントを開始します0から0を返します – Rocky

+0

@Rocky: '0'からではなく' + 1'を追加するだけです(私の編集を見てください)。行インデックス –

+0

と同じですが、chunk.index + 1はチャンクではありません。count + 1、columnCount + 1 – Rocky

0
System.IO.StreamReader file = new System.IO.StreamReader("c:\\file.txt"); 
while((line = file.ReadLine()) != null) 
{ 

} 

ここで、あなたのラインを任意のセプレータと分けることができます。

3
char delimiter = ','; // This can be modified 
int numberOfCols = 6; // this will be the number of columns per row 

var lines = File 
    .ReadLines("Path here") 
    .Where(l => l.Split(delimiter).Count() == numberOfCols); 

これは、指定した数の列を含む行を含むコレクションを提供します。あなたは、列の実際の数を知っているが、この未知の数は、すべての行に対して同じであることを確認したくない場合

var invalidLines = File 
    .ReadLines("Path here") 
    .Select((l, lineNumber) => new { key = lineNumber, value = l }) 
    .Where(l => l.value.Split(delimiter).Count() != numberOfCols); 
+0

列の数を知らない – Rocky

+0

システムが '列の数を知らない場合は' –

+0

システムは区切り文字に基づいて列を取得する必要があります。 – Rocky

関連する問題