【问题标题】:How to read the null string with Streamreader c#如何使用 Streamreader c# 读取空字符串
【发布时间】: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


【解决方案1】:

如果我们把:

athlete.Agency_Code = Records[5];

与(来自 cmets)一起:

该列是引用另一个表 PK 的 FK,它可以接受空值。

问题变得清晰起来。空字符串 ("") 不是 null;它是一个空字符串!听起来你只是想要这样的东西:

var agencyCode = Records[5];
athlete.Agency_Code = string.IsNullOrEmpty(agencyCode) ? null : agencyCode;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-16
    相关资源
    最近更新 更多