0

I have integrated the pcsc library to work with an nfc scanner (ACR122U ISO14443A/B ). I am trying to read the data from the NFC tag, but I get this error: An error has occurred: An attempt was made to end a non-existent transaction.

How can I fix this?

using System;
using PCSC;
using PCSC.Iso7816;

class Program
{
    static void Main()
    {
        try
        {
            var contextFactory = ContextFactory.Instance;
            using (var context = contextFactory.Establish(SCardScope.System))
            {
                var readerNames = context.GetReaders();
                if (readerNames.Length == 0)
                {
                    Console.WriteLine("Keine Leser gefunden.");
                    return;
                }

                var readerName = readerNames[0];
                Console.WriteLine(readerName);
                using (var isoReader = new IsoReader(context, readerName, SCardShareMode.Shared, SCardProtocol.Any, false))
                {
                    Console.WriteLine(isoReader);
                    var apdu = new CommandApdu(IsoCase.Case2Short, isoReader.ActiveProtocol)
                    {
                        CLA = 0x00,
                        Instruction = InstructionCode.GetData,
                        P1 = 0x00,
                        P2 = 0x00,
                        Le = 0x00 // Le = 0x00 bedeutet, dass wir die maximale Anzahl von Bytes erwarten
                    };
                    Console.WriteLine(apdu);

                    var response = isoReader.Transmit(apdu);
                    Console.WriteLine(response);
                    if (response.HasData)
                    {
                        Console.WriteLine("Daten vom NFC-Tag:");
                        Console.WriteLine(BitConverter.ToString(response.GetData()));
                    }
                    else
                    {
                        Console.WriteLine($"Fehler beim Lesen des NFC-Tags: SW1 SW2 = {response.SW1:X2} {response.SW2:X2}");
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Ein Fehler ist aufgetreten: {ex.Message}");
        }
    }
}

Read data of the nfc tag. I have worked a lot with copilot as I have no experience with this library and C#. It is therefore possible that the code is bad or faulty.

2
  • Yes copilot has produced bad code, the APDU looks wrong, may be read the datasheet for the reader acs.com.hk/download-manual/419/API-ACR122U-2.04.pdf to work out the correct commands you need to send to get the reader to do what you want.
    – Andrew
    Commented Jul 10 at 13:13
  • Thanks, I have now changed the Adpu command and can read out the tag! Commented Jul 12 at 7:00

0

Browse other questions tagged or ask your own question.