0

I have a code to read data block inside MIFARE card.

The method rfidM1.ReadDataFromCardM1 will read a block and return value in string.

string memQuery = string.Empty;
int i = 0, j = 0;
sector = 4;
block = 4;

for (i = 0; i < block; i++)
{
    for (j = 0; j < sector; j++)
    {                  
        memQuery += rfidM1.ReadDataFromCardM1(Convert.ToByte(j), Convert.ToByte(i), _Key1) + ",";
    }
}          

My intention is concating memQuery with comma. Example output here:

,0,,,,,True,,C0-12320,0,,,,,,

I concat memQuery with various ways, for example, using +=, StringBuilder or ArrayList but they didn't work because it always has an output like this when I put it in MessageBox.

,0

It looks like string after that 0 cannot concat with other string after it. Why?

11
  • 1
    Try and use a List<string> (which contains real strings) instead of an ArrayList (which contains just objects) Commented May 4, 2018 at 8:44
  • I'm getting confused with that memQuery.Add. Is that a collection? Try refactoring your code. What are the variables and values you want to concat to that string? K ? You're near it smells weird near that .ToString().Replace() . Try creating different methods for each purpose so it will be easier to debug the problem. Commented May 4, 2018 at 8:46
  • OT the usual way to declare an index variable of a for statement is inside it: for (int i=0; .... And you could also declare it as byte if that is what you really need Commented May 4, 2018 at 8:50
  • @HansKesting I tried it with List<string> and got the same result. Commented May 4, 2018 at 8:53
  • 1
    if memQuery[k] returns null, you will get a NullReferenceException when trying to execute any method on it, such as GetType() or ToString(). Could that ReadDataFromCardM1 return nulls or control characters? Commented May 4, 2018 at 9:00

1 Answer 1

1

My intention is concating memQuery with comma

Wel, first get rid of the ArrayList and replace it with var memQuery = new List<string>();.

Inside your for-loops, decide what to with null or empty results. Add a null or skip the Add or ...

And then when the memQuery is filled correctly, you can do

 string result = string.Join(",", memQuery);

string.Join() can handle nulls in the input sequence.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer. It turned out those return string have control characters inside them. I removed them by following this thread stackoverflow.com/a/15259355/4535654 and it works now.
Then maybe they were not strings at all... It all depends on what you want to show.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.