【问题标题】:How to check if string is null in c#.net [duplicate]如何在c#.net中检查字符串是否为空[重复]
【发布时间】:2016-11-23 08:02:36
【问题描述】:

我正在阅读 c#.net 中的文本文件 最后一行完全为空,但在 foreach c# 中无法检测到空字符串,因此出现错误

string[] lines = System.IO.File.ReadAllLines(dir);
List<KeyValuePair<int, DateTime>> items = new List<KeyValuePair<int, DateTime>>();
List<KeyValuePair<int, DateTime>> lst = new List<KeyValuePair<int, DateTime>>();
foreach (string line in lines)
{
    if (line!=string.Empty)
    {
        l = line.Split('\t');
        l[0] = l[0].Trim();
        PersianCalendar persCal = new PersianCalendar();
        SqlConnection sqlconn = new SqlConnection(DBsetting.Connstring);
        SqlCommand sqlda = new SqlCommand("InsertReadd", sqlconn);
        sqlda.CommandType = CommandType.StoredProcedure;
        sqlda.Parameters.AddWithValue("@date", l[1]);
        sqlda.Parameters.AddWithValue("@IDp", l[0]);
        sqlda.Parameters.AddWithValue("@day", GetDayOfWeek(GetPerDate(l[1])));
        sqlda.Parameters.AddWithValue("@nobatkari", "");
        sqlda.Connection.Open();
        sqlda.ExecuteNonQuery();
        sqlda.Connection.Close();
    }
}
RefGrid();

【问题讨论】:

  • 你在找String.IsNullOrEmpty
  • 你应该包括你实际得到的错误。
  • string.IsNullOrWhiteSpace 是个不错的选择

标签: c# string file nul


【解决方案1】:
if(!String.IsNullOrEmpty(line))

只要这样做就可以了

它检查 Null 和 Empty。这是 C# 中此功能随处使用的。

编辑: 您可以使用以下内容检查包含空格的字符串。

if(!String.IsNullOrWhiteSpace(line))

【讨论】:

  • 我测试了它。它不起作用
  • @javad 请显示你得到的错误
  • 我没有收到错误,但是当行为空时,它会从 if 子句传递
  • @javad 我猜该行充满了空格。你确定吗。请给出一个清晰的思路。我会解决的
  • 是的,这是真的。该行充满了空格,我正在使用 foreach 循环读取文本文件的行
【解决方案2】:

CHECK

改变:

 if (line!=string.Empty)

到:

  //check if the sting = null or empty
  if (!String.IsNullOrEmpty(line))
  { 
     //some code 
  }

【讨论】:

    猜你喜欢
    • 2013-01-30
    • 2013-03-07
    • 2014-07-06
    • 2018-10-17
    • 2018-07-19
    • 1970-01-01
    • 2019-06-06
    • 2019-08-05
    • 2016-09-13
    相关资源
    最近更新 更多