Equivalente a TextFieldParser in .NET?

Esiste un moderno .NET equivalente alla class TextFieldParser in VB6? Le prestazioni sono molto inferiori rispetto a un semplice String.Split()

Ho confrontato le prestazioni con quel codice: https://gist.github.com/Ruszrok/7861319

Ho usato un file di input con circa 1 000 000 di record separati da spazi. Ho provato cinque esperimenti.

  • String.Split tempo medio: 291 ms
  • Microsoft.VisualBasic.FileIO.TextFieldParser tempo medio: 15843 ms

È ansible utilizzare la class Microsoft.VisualBasic.FileIO.TextFieldParser . Riferimento Microsoft.VisualBasic . Campione in sintesi.

Questa è la mia soluzione:

 public class TextFieldParser { enum FieldType { FixedWidth, Delimited }; public enum CompleteElements { ///  /// Returns as many elements as fileWidths input be ///  AllElements, ///  /// Only returns elements who have not null values ///  OnlyValues }; int[] m_fieldWidths; string m_line; List m_results; int m_lineWidth; public CompleteElements m_CompleteElements; public TextFieldParser(string line) { m_line = line; m_lineWidth = m_line.Length; m_results = new List(); m_CompleteElements = CompleteElements.OnlyValues; } public void SetCompleteElements(CompleteElements value) { m_CompleteElements = value; } public void SetFieldWidths(params int[] fileWidths) { m_fieldWidths = fileWidths; } public string[] ReadFields() { int pivot = 0; m_results = new List(); for (int x = 0; x < m_fieldWidths.Length; x++) { if(pivot + m_fieldWidths[x] <= m_lineWidth) { m_results.Add(m_line.Substring(pivot, m_fieldWidths[x])); } else { if (m_CompleteElements == CompleteElements.AllElements) { m_results.Add(null); } break; } pivot += m_fieldWidths[x]; } return m_results.ToArray(); } } 

Una sessione semplice:

 string line = "1234567890123456789012345678890"; TextFieldParser parser = new TextFieldParser(line); parser.SetFieldWidths(1, 2, 3, 4, 5, 6, 7, 8); string[] resultOnlyValues = parser.ReadFields(); /* results: resultOnlyValues[0] : "1" resultOnlyValues[1] : "23" resultOnlyValues[2] : "456" resultOnlyValues[3] : "7890" resultOnlyValues[4] : "12345" resultOnlyValues[5] : "678901" resultOnlyValues[6] : "2345678" */ parser.SetCompleteElements(TextFieldParser.CompleteElements.AllElements); string[] resultAllElement = parser.ReadFields(); /* results: resultAllElement[0] : "1" resultAllElement[1] : "23" resultAllElement[2] : "456" resultAllElement[3] : "7890" resultAllElement[4] : "12345" resultAllElement[5] : "678901" resultAllElement[6] : "2345678" resultAllElement[7] : null */