dotnet - Read a .csv in .NET
Published: Dotnet Estimated reading time: ~1 minutes
// Namespace: Microsoft.VisualBasic.FileIO
// https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.textfieldparser%28v=vs.110%29.aspx
// Assembly: Microsoft.VisualBasic (in Microsoft.VisualBasic.dll)
private static List<SourceDocument> ReadCSV(string p) {
List<SourceDocument> docs = new List<SourceDocument>();
using (TextFieldParser parser = new TextFieldParser(p)) {
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
while (!parser.EndOfData) {
//Processing row
string[] fields = parser.ReadFields();
if (fields[0].Trim().ToUpper() != "HEADER1NAME") {
SourceDocument doc = new SourceDocument();
doc.StringField = fields[0].Trim();
doc.IntField = Convert.ToInt32(fields[1]);
doc.DateField = Convert.ToDateTime(fields[2]);
docs.Add(doc);
}
}
}
return docs;
}