Reputation: 473
I am creating a CSV Importing tool (comma separated). I am trying to make this importing tool as generic as possible , so that it can process any CSV File.
I have almost finalised the tool , but came across one file which I am finding it difficult to process.
How can I process the file with data in following format?
column1,column2,column3,column4,column5
----------
alex,p,22323,23232,hello
mike,t,"121212,232323,4343434",33432,hi
guna,s,"2423,2332",whats
cena,a,34443,33432,up
Since the file is comma separated, and one of its value is comma separated as well between identifier "value,value,value"
I am finding it difficult to process.
How can i tackle this issue?
I donot have control over CSV file. So I cant change the format
Upvotes: 0
Views: 249
Reputation: 120450
As per @dtb... use a CSV parser. If you reference Microsoft.VisualBasic
then you can:
var data=@"column1,column2,column3,column4,column5
----------
alex,p,22323,23232,hello
mike,t,""121212,232323,4343434"",33432,hi
guna,s,""2423,2332"",whats
cena,a,34443,33432,up";
using (var sr = new StringReader(data))
using (var parser =
new TextFieldParser(sr)
{
TextFieldType = FieldType.Delimited,
Delimiters = new[] { "," },
CommentTokens = new[] { "--" }
})
{
while (!parser.EndOfData)
{
string[] fields;
fields = parser.ReadFields();
//yummy
}
}
This deals with quotes correctly.
Upvotes: 2