【发布时间】:2021-03-27 21:42:54
【问题描述】:
我想根据标题动态读取文本文件。考虑这样的例子
name|email|phone|othername|company
john|john@example.com|1234||example
doe|doe@example.com||pin
jane||98485|
下面的记录要这样读取的值
name email phone othername company
john john@example.com 1234 example
doe doe@example.com pin
jane 98485
我试过用这个
using (StreamReader sr = new StreamReader(new MemoryStream(textFile)))
{
while (sr.Peek() >= 0)
{
string line = sr.ReadLine(); //Using readline method to read text file.
string[] strlist = line.Split('|'); //using string.split() method to split the string.
Obj obj = new Obj();
obj.Name = strlist[0].ToString();
obj.Email = strlist[1].ToString();
obj.Phone = strlist[2].ToString();
obj.othername = strlist[3].ToString();
obj.company = strlist[4].ToString();
}
}
如果所有分隔符都被准确放置,上面的代码就可以工作,但是当像上面那样动态给出时,上面的代码就不起作用了。有什么可能的解决方案吗?
【问题讨论】:
-
什么是“不起作用”,会发生什么,“动态”是什么意思?您的意思是列名可能不同,您要查找的数据可能位于其他位置?
-
不,我的意思是如果给定的文本文件只有两列的数据,它就不起作用。如果文本文件只有 2 列,则不会读取它们
-
c# 4.0?真的吗?
-
在使用特定索引之前检查数组长度,以确保您没有遇到 Index out of Range 异常。
-
@VDWWD 但我将获得不同数量的数据。只有标题会被修复。