我使用此代码省略引号并用逗号分隔。
我有像这样的数据的csv文件的内容。
例如:
“1111”,“05-24-2017”,“08:30”,“0”,“TRAVEL”
“2222”, “2017年5月25日”, “8时20”, “0”, “旅行”
我使用了这段代码:
public bool ReadEntrie(int id, ref string name)
{
int count = 0;
CreateConfigFile();
try
{
fs = new FileStream(data_path, FileMode.Open);
sr = new StreamReader(fs);
bool cond = true;
string temp = "";
while (cond == true)
{
if ((temp = sr.ReadLine()) == null)
{
sr.Close();
fs.Close();
cond = false;
if (count == 0)
return false;
}
if (count == id)
{
string[] stringSplit = temp.Trim('\"').Split(new
String[] { "," }, StringSplitOptions.None);
//string[] stringSplit = temp.Split(',');
int _maxIndex = stringSplit.Length;
name = stringSplit[0];
}
count++;
}
sr.Close();
fs.Close();
return true;
}
catch
{
return false;
}
}
答案 0 :(得分:1)
如果没有 逗号或引号作为数据的一部分,例如
"12,34","56","a""bc" -> 12,34 56 a"bc
你可以放一个简单的 Linq :
string[][] result = File
.ReadLines(@"C"\MyData.csv")
.Select(line => line
.Split(',')
.Select(item => item.Trim('"'))
.ToArray())
.ToArray();
进一步改进是返回一个定制类的数组:
MyClass[] result = File
.ReadLines(@"C"\MyData.csv")
.Select(line => line
.Split(','))
.Select(items => new MyClass() {
Id = items[0].Trim('"'),
Date = DateTime.ParseExact(items[1].Trim('"') + " " + items[2].Trim('"'),
"MM-dd-yyyy hh:mm",
CultureInfo.InvariantCulture),
Code = items[3].Trim('"'),
Text = items[4].Trim('"'),
})
.ToArray();
答案 1 :(得分:0)
The problem is not on that function. It is by other function and I used trim
for it.
string[] stringSplit = temp.Split(',');
int _maxIndex = stringSplit.Length;
name = stringSplit[0].Trim('"');
lastname = stringSplit[1].Trim('"');
phone = stringSplit[2].Trim('"');
mail = stringSplit[3].Trim('"');
website = stringSplit[4].Trim('"');
答案 2 :(得分:0)
尝试这个简单的功能。它将处理双引号之间的双引号和逗号。
private string[] GetCommaSeperatedWords(string sep, string line)
{
List<string> list = new List<string>();
StringBuilder word = new StringBuilder();
int doubleQuoteCount = 0;
for (int i = 0; i < line.Length; i++)
{
string chr = line[i].ToString();
if (chr == "\"")
{
if (doubleQuoteCount == 0)
doubleQuoteCount++;
else
doubleQuoteCount--;
continue;
}
if (chr == sep && doubleQuoteCount == 0)
{
list.Add(word.ToString());
word = new StringBuilder();
continue;
}
word.Append(chr);
}
list.Add(word.ToString());
return list.ToArray();
}