2010-05-10 5 views
1

Ce que je dois faire est de lire un fichier texte spécifique et de retirer toute la colonne en fonction d'une chaîne.Lecture d'un fichier texte et extraction de colonnes spécifiques

Donc, si ma chaîne était parkingfee je tirerais n'importe quelle colonne dans mon | fichier délimité cette ligne d'en-tête correspond au mot parkingfee

+1

Bon si vous avez besoin d'analyser un fichier texte. Quelle est votre question? –

Répondre

1

Cela devrait faire l'affaire pour vous. Pour faire ce que vous voudriez, vous pouvez le faire:

foreach(string val in GetColumnValues(fileName, "parkingfee", "|") 
{ 
    ... 
} 

est ici la fonction:

public static IEnumerable<string> GetColumnValues(string fileName, string columnName, string delimiter) 
{ 
    using (System.IO.StreamReader reader = new System.IO.StreamReader(fileName)) 
    { 
     string[] delim = new string[] { delimiter }; 

     string[] columns = reader.ReadLine().Split(delim, StringSplitOptions.None); 

     int column = -1; 

     for (int i = 0; i < columns.Length; i++) 
     { 
      if (string.Compare(columns[i], columnName, true) == 0) 
      { 
       column = i; 
       break; 
      } 
     } 

     if (column == -1) throw new ArgumentException("The specified column could not be found."); 

     while (reader.BaseStream.Position < reader.BaseStream.Length) 
     { 
      string[] line = reader.ReadLine().Split(delim, StringSplitOptions.None); 

      if (line.Length > column) yield return line[column]; 
     } 
    } 
} 
Questions connexes