【发布时间】:2018-04-15 21:03:36
【问题描述】:
我正在读取包含以下数据的文件
123456788|TUUKKA|RASK|01/01/85|HOCKEY|123
123456786|TOM|BRADY|01/01/75|FOOTBALL|123
123456787|RAJON|RONDO|01/01/80|BASKETBALL|ABC
123456785|DUSTIN|PEDROIA|01/01/83|BASEBALL|
123456789|DAVID|ORTIZ|01/01/77|BASEBALL|123
并用分隔符“|”分割它,但我是流阅读器,没有读取最后包含 null 的第 4 行。我该如何处理?
这是我读取和分割文本文件行的代码
string s = string.Empty;
using (System.IO.StreamReader File = new System.IO.StreamReader(Path))
{
File.ReadLine();//Removing the first line
while ((s = File.ReadLine()) != null)
{
string[] str = s.Split('|');
UpdateRecords.Athelete(str);
}
}
这是我的UpdateRecords.Athelete(str) 代码:
public static void Athelete(string[] Records) {
tblAthlete athlete = new tblAthlete();
using (SportEntities sportEntities = new SportEntities()) {
var temp = Convert.ToInt32(Records[0]);
if (sportEntities.tblAthletes.FirstOrDefault(x => x.SSN == temp) == null) {
athlete.SSN = Convert.ToInt32(Records[0]);
athlete.First_Name = Records[1];
athlete.Last_Name=Records[2];
athlete.DOB = Convert.ToDateTime(Records[3]);
athlete.SportsCode = Records[4];
athlete.Agency_Code = Records[5];
sportEntities.tblAthletes.Add(athlete);
sportEntities.SaveChanges();
}
}
}
【问题讨论】:
-
“不读行”是什么意思?当你说“最后包含一个空值”时,你到底是什么意思? (行尾是否有 U+0000 字符,或者您的意思是在
|之后没有任何内容?) -
你可以使用不同的重载 split
.Split("|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); -
是的,'|'后面没有值在第 4 行的末尾。
-
|之后没有值(而不是nul字符),它不会是“删除第 4 行” - 我猜它是你的UpdateRecords.Athelete(str);方法正在这样做......但我们看不到那个方法! -
@Kushal 不,没有这样的事情
The streamreader is just removing the 4th line and proccessing all other lines properly.
标签: c# null streamreader