Why is the else branch not executing?

This is a really working application. Although without a special way to capture errors.

I'm just trying to register a stream, and I have not reached the If branch, nor the else branch. What can I do to make this happen? None of the branch branches are included in my txt file.

while (reader.Read()) { if (reader.HasRows) { LogMessage("Further Inside Try2 "); byte[] paymentData = (byte[])reader["payment"]; strPaymentData = ASCIIEncoding.Unicode.GetString(paymentData); LogMessage(strPaymentData + " strPaymentData"); } else { LogMessage("Payment Retrievlal Failed "); } } 
+4
source share
6 answers

You do not need to check if the reader has strings if you use while reader.read (). If the reader does not return a row, the while loop will not execute. Consequently, another will never be achieved if the reader has no lines.

You can rewrite your code as follows:

 if (reader.HasRows) { while (reader.Read()) { LogMessage("Further Inside Try2 "); byte[] paymentData = (byte[])reader["payment"]; strPaymentData = ASCIIEncoding.Unicode.GetString(paymentData); LogMessage(strPaymentData + " strPaymentData"); } } else { LogMessage("Payment Retrievlal Failed "); } 
+11
source

reader.Read() returns false if there are no lines to read. Thus, if you want to perform special processing without returning strings, you will need to move this check outside the while :

  if (reader.HasRows()) { while (reader.Read()) { LogMessage("Further Inside Try2 "); byte[] paymentData = (byte[])reader["payment"]; strPaymentData = ASCIIEncoding.Unicode.GetString(paymentData); LogMessage(strPaymentData + " strPaymentData"); } } else { LogMessage("Payment Retrievlal Failed "); } 

Now, if , you know that only 1 row is returned (for example, reading on the primary key), you can simplify the code by simply placing reader.Read() inside if :

 if (reader.Read()) { LogMessage("Further Inside Try2 "); byte[] paymentData = (byte[])reader["payment"]; strPaymentData = ASCIIEncoding.Unicode.GetString(paymentData); LogMessage(strPaymentData + " strPaymentData"); } else { LogMessage("Payment Retrievlal Failed "); } 
+7
source

If you just read a line successfully , then obviously there are at least 1 line, so HasRows will return true. Move the HasRows test outside of "while"

+2
source

If you have not reached either of the two branches, this should be because reader.Read()) returns false . I see no other way to do this.

+2
source

Probably your call to reader.Read () detects that there are no lines, either because the file is for some reason not open or empty. Therefore, checking for new HasRows after reading does not work as you expect.

0
source

Label the logic:

 if (reader.HasRows) { while (reader.Read()) { //Process a row } else { LogMessage("Payment Retrievlal Failed "); } 
0
source

Source: https://habr.com/ru/post/1385597/


All Articles