使用逗号分隔符读取csv文件c# [英] Read csv file c# with comma separator
本文介绍了使用逗号分隔符读取csv文件c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试读取格式如下的csv文件:
name,location
Joseph,street xpto,London
当我读取CSV时,我将文件分割为,,但当行有street xpto,London(其他逗号)时,它不起作用。
有什么解决方案吗?我需要在找到一个时忽略逗号。
var reader = new StreamReader(File.OpenRead :\example_File.csv));
while(!reader.EndOfStream)
{
var line = reader.ReadLine();
String [] values = line.Split(',');
for(int i = 0; i{
}
}
解决方案文本字段解析器已处理此问题
using System;
using Microsoft.VisualBasic.FileIO;
类程序
{
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);
}
}
}
}
I'm trying to read an csv file with the format: name, location Joseph, "street xpto, London"
When I read CSV, I split the file to ",", but when the line has "street xpto, London" (other commas) it doesn't work.
Is there some solution to that? I need to do split ignoring commas when find an " ".
var reader = new StreamReader(File.OpenRead(@"C:\example_File.csv")); while (!reader.EndOfStream) { var line = reader.ReadLine(); String[] values = line.Split(','); for (int i = 0; i < values.Length; i++) { } }
解决方案Text field parser handles this already
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); } } } }
这篇关于使用逗号分隔符读取csv文件c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文