C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: To access TextFieldParser, go to Add Reference, and select Microsoft.VisualBasic.
Further: We show the ReadFields method, which returns null when the end of file condition is met.
And: In the result, the array returned contains every field in its own element. We display the length.
C# program that uses TextFieldParser
using System;
using Microsoft.VisualBasic.FileIO;
class Program
{
static void Main()
{
using (TextFieldParser parser = new TextFieldParser("C:\\csv.txt"))
{
parser.Delimiters = new string[] { "," };
while (true)
{
string[] parts = parser.ReadFields();
if (parts == null)
{
break;
}
Console.WriteLine("{0} field(s)", parts.Length);
}
}
}
}
Input file: csv.txt
a,b,c
d,e,f
gh,ij
Output
3 field(s)
3 field(s)
2 field(s)
C# program that benchmarks TextFieldParser
using System;
using System.Diagnostics;
using System.IO;
using Microsoft.VisualBasic.FileIO;
class Program
{
const int _max = 10000;
static void Main()
{
Method1();
Method2();
System.Threading.Thread.Sleep(1000);
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
Method1();
}
s1.Stop();
var s2 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
Method2();
}
s2.Stop();
Console.WriteLine(s1.Elapsed.TotalMilliseconds);
Console.WriteLine(s2.Elapsed.TotalMilliseconds);
}
static void Method1()
{
using (TextFieldParser parser = new TextFieldParser("C:\\csv.txt"))
{
parser.Delimiters = new string[] { "," };
while (true)
{
string[] parts = parser.ReadFields();
if (parts == null)
{
break;
}
// Console.WriteLine("{0} field(s)", parts.Length);
}
}
}
static void Method2()
{
char[] delimiters = new char[] { ',' };
using (StreamReader reader = new StreamReader("C:\\csv.txt"))
{
while (true)
{
string line = reader.ReadLine();
if (line == null)
{
break;
}
string[] parts = line.Split(delimiters);
// Console.WriteLine("{0} field(s)", parts.Length);
}
}
}
}
Result with 3-line, 8-field file
2616 ms
623 ms
Result with 300-line, 800-field file
10762 ms
1186 ms
However: We revealed the performance characteristics of TextFieldParser. It is slow and becomes yet slower on larger files.