-1

I am reading text file in c#.net at the end one line is completely null but in foreach c# can not detect null string so It gets error

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();
Radinator
  • 1,048
  • 18
  • 58
javad
  • 11
  • 1
  • 1

2 Answers2

2
if(!String.IsNullOrEmpty(line))

just do this and it works

It checks for Null and Empty. This is the used everywhere for this functionality in C#.

EDIT: You can use the following for checking strings which contains whitespaces.

if(!String.IsNullOrWhiteSpace(line))
Noxious Reptile
  • 838
  • 1
  • 7
  • 24
0

CHECK

change:

 if (line!=string.Empty)

to:

  //check if the sting = null or empty
  if (!String.IsNullOrEmpty(line))
  { 
     //some code 
  }
Timon Post
  • 2,779
  • 1
  • 17
  • 32