-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();
3
  • 1
    are you looking for String.IsNullOrEmpty Commented Nov 23, 2016 at 8:03
  • You should include what error you actually get. Commented Nov 23, 2016 at 8:05
  • string.IsNullOrWhiteSpace is a good choice Commented Nov 23, 2016 at 8:13

2 Answers 2

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))
Sign up to request clarification or add additional context in comments.

6 Comments

I test it .it doesnot work
@javad please show the error u get
I get no error but when line is empty it passes from if clause
@javad I guess the line is full of Whitespaces. Can you confirm. Please give a clear idea. I will solve it
Yes that's true.the line is full of Whitespaces,I am reading lines of a text file with foreach loop
|
0

CHECK

change:

 if (line!=string.Empty)

to:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.