TextFieldParser等效于.NET?

是否有一个与VB6中的TextFieldParser类等效的现代.NET? 性能远低于简单的String.Split()

我已将性能与该代码进行了比较: https : //gist.github.com/Ruszrok/7861319

我使用了一个输入文件,其中大约有1 000 000条记录用空格分隔。 我尝试了五次实验。

  • String.Split平均时间: 291毫秒
  • Microsoft.VisualBasic.FileIO.TextFieldParser平均时间: 15843毫秒

您可以使用Microsoft.VisualBasic.FileIO.TextFieldParser类。 参考Microsoft.VisualBasic 。 要点中的样本。

这是我的解决方案:

 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(); } } 

一个简单的会话:

 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 */