How to Read a Smart Card UID Using C#

How do you read a card UID in C#? Wait until the contactless (PICC) reader reports a card with SCardGetStatusChange, connect with SCardConnect in shared mode, and send the PC/SC Get Data command FF CA 00 00 00 with SCardTransmit. The reply is the UID followed by the status word 90 00. Before connecting, the card's ATR already tells you what kind of card it is. Contact cards, such as those in an ACR39U, have no UID in this sense: read their ATR instead, and do not send FF CA to them.

This guide turns that into a .NET 10 tap-to-read loop for attendance, access or canteen-style programs: one read per tap, ATR decoding, UID output in the formats other systems use, and clean handling of cards pulled away too early. It uses the shared files from PC/SC smart card programming in C#.

Which page do you need? To read a UID once without code, or to understand why one card shows as A1B2C3D4, D4C3B2A1 or a decimal number, see reading an NFC card UID with an ACS reader. For a minimal one-shot C# example for a single model, see the ACR1252U, ACR1552U or ACR122U SDK page. This page is the continuous version, for any ACS contactless reader.

The usual mistake in UID code is to connect in a loop until it works. That uses CPU, holds the card longer than needed and reads the same card many times. The event-driven version is shorter and behaves better:

  1. Pick the reader by name: the first ACS entry containing PICC, or the part of a name you pass as an argument. Matching ACS reader names explains the rules.
  2. Read the current state once (time-out 0). A card already on the reader is read straight away.
  3. Act only when a card arrives: the state changes to PRESENT from not present. The ATR is already in the reader-state entry, so print and decode it before connecting.
  4. Connect, send FF CA 00 00 00, disconnect with SCARD_LEAVE_CARD. The connection is open for a few milliseconds.
  5. Wait with INFINITE for the next change. Removing the card produces EMPTY, which re-arms step 3. A card left on the reader is not read again.

A card that leaves the field between "present" and the transmit gives SCARD_W_REMOVED_CARD; the loop reports it and waits for the next tap instead of stopping. A MUTE state means the reader sees a card that does not answer, so no connection is attempted.

Language: C# 14 on .NET 10, Windows only (P/Invoke to winscard.dll). Prerequisites: a console project with WinScard.cs and Pcsc.cs (setup steps); an ACS contactless reader such as the ACR1252U, ACR1552U or ACR122U with the ACS driver; cards such as MIFARE Classic 1K, NTAG or DESFire. Run dotnet run, or dotnet run -- ACR1552 to choose a reader. To see the contact-card path, pass part of an ACR39U name, for example dotnet run -- ACR39.

The program is read-only. It sends Get Data and nothing else, and only to a PICC reader. It reads no card memory, loads no keys and writes nothing.

Compiled by BSD; not yet tested on a reader. Built for net10.0 on 1 Dec 2026 with 0 warnings and 0 errors. BSD ran it on a Windows 11 PC without an ACS reader, where it correctly reported "No matching reader" and listed the readers it saw. Runs with ACS readers and MIFARE Classic, NTAG, DESFire and SLE cards are still to be done; the ATR names below are from the ACS manuals, not from BSD's readers.

// Day 37: read the UID of every card tapped on a contactless reader. C# 14, .NET 10, Windows only.
// Needs WinScard.cs and Pcsc.cs in the same project. Compiled by BSD; not yet tested on a reader.
// Read-only: the only command sent is Get Data FF CA 00 00 00, and only on a contactless (PICC) reader.
// On a contact reader (for example an ACR39U) it shows the ATR from the reader state and sends nothing.
using System;
using System.Linq;
using System.Numerics;
using System.Threading;
using Bsd.Pcsc;

using var cts = new CancellationTokenSource();
Console.CancelKeyPress += (_, e) => { e.Cancel = true; cts.Cancel(); };

try
{
    using var pcsc = new PcscContext();
    string[] readers = pcsc.ListReaders();
    // Reader choice: the argument if given, else the first ACS contactless entry, else any PICC entry.
    string? reader = args.Length > 0
        ? readers.FirstOrDefault(r => r.Contains(args[0], StringComparison.OrdinalIgnoreCase))
        : readers.FirstOrDefault(r => r.StartsWith("ACS ", StringComparison.OrdinalIgnoreCase) && r.Contains("PICC", StringComparison.OrdinalIgnoreCase))
          ?? readers.FirstOrDefault(r => r.Contains("PICC", StringComparison.OrdinalIgnoreCase));
    if (reader is null)
    {
        Console.WriteLine("No matching reader. Readers seen: " + (readers.Length == 0 ? "none" : string.Join(" | ", readers)));
        return 1;
    }
    bool contactless = reader.Contains("PICC", StringComparison.OrdinalIgnoreCase);
    Console.WriteLine($"Reader: {reader} ({(contactless ? "contactless" : "contact")}). Tap cards; Ctrl+C to stop.");

    var state = new[] { PcscContext.NewState(reader) };
    pcsc.WaitForChange(state, 0, cts.Token);            // current state, at once
    while (true)
    {
        uint s = state[0].dwEventState;
        if ((s & (WinScard.SCARD_STATE_UNKNOWN | WinScard.SCARD_STATE_UNAVAILABLE)) != 0)
        {
            Console.WriteLine("The reader was removed.");
            return 3;
        }
        // Act once per card: when PRESENT appears. pcsc-lite also counts insertions and removals in the
        // upper 16 bits, so a quick card swap changes that count even if PRESENT never cleared.
        uint was = state[0].dwCurrentState;
        bool arrived = (s & WinScard.SCARD_STATE_PRESENT) != 0
                       && ((was & WinScard.SCARD_STATE_PRESENT) == 0 || (was & 0xFFFF0000) != (s & 0xFFFF0000));
        if (arrived)
        {
            byte[] atr = PcscContext.Atr(state[0]);
            Console.WriteLine();
            Console.WriteLine($"{DateTime.Now:HH:mm:ss} Card present. ATR: {Apdu.HexSpaced(atr)}");
            Console.WriteLine("   " + AtrInfo.Describe(atr));
            if ((s & WinScard.SCARD_STATE_MUTE) != 0) Console.WriteLine("   The card does not answer (MUTE). Try another card.");
            else if (contactless) ReadUid(pcsc, reader);
            else Console.WriteLine("   Contact card: no anti-collision UID, so FF CA is not sent. See the ATR above.");
        }
        PcscContext.Acknowledge(state);
        pcsc.WaitForChange(state, WinScard.INFINITE, cts.Token);   // next arrival or removal
    }
}
catch (OperationCanceledException)
{
    Console.WriteLine("Stopped.");
    return 0;
}
catch (PcscException ex)
{
    Console.WriteLine(ex.Message);
    return 1;
}

static void ReadUid(PcscContext pcsc, string reader)
{
    try
    {
        using var card = pcsc.Connect(reader);         // shared mode, T=0 or T=1
        byte[] reply = card.Transmit(Apdu.GetUid);
        if (!Apdu.IsSuccess(reply))
        {
            Console.WriteLine($"   Get Data refused: status word {Apdu.StatusWord(reply)} (63 00 = failed, 6A 81 = not supported).");
            return;
        }
        byte[] uid = Apdu.Data(reply);
        byte[] reversed = uid.Reverse().ToArray();
        Console.WriteLine($"   UID ({uid.Length} bytes) as returned: {Apdu.Hex(uid)}");
        Console.WriteLine($"   UID bytes reversed:          {Apdu.Hex(reversed)}");
        Console.WriteLine($"   Decimal, as returned:        {new BigInteger(uid, isUnsigned: true, isBigEndian: true)}");
        Console.WriteLine($"   Decimal, reversed:           {new BigInteger(reversed, isUnsigned: true, isBigEndian: true)}");
        if (uid.Length == 4 && uid[0] == 0x08) Console.WriteLine("   Starts with 08: may be a random ID that changes on every tap.");
    }
    catch (PcscException ex) when (ex.Code is WinScard.SCARD_W_REMOVED_CARD or WinScard.SCARD_E_NO_SMARTCARD)
    {
        Console.WriteLine("   The card left the field before it could be read. Hold it still and tap again.");
    }
    catch (PcscException ex) when (ex.Code == WinScard.SCARD_E_SHARING_VIOLATION)
    {
        Console.WriteLine("   Another program holds the card (sharing violation). Close other card tools.");
    }
}

static class AtrInfo
{
    // PC/SC Part 3 builds an ATR for contactless cards: 3B 8n 80 01 + n historical bytes + TCK.
    // Storage cards (MIFARE Classic, Ultralight ...) carry 80 4F 0C A0 00 00 03 06 SS C0 C1 00 00 00 00 in those bytes.
    // Card-name values below are from the ACS ACR1552U reference manual v1.05 (5.3.1.1) and ACR122U API manual v1.4 (3.1.1).
    public static string Describe(byte[] atr)
    {
        if (atr.Length < 5) return "ATR too short to decode.";
        bool constructed = atr[0] == 0x3B && (atr[1] & 0xF0) == 0x80 && atr[2] == 0x80 && atr[3] == 0x01;
        if (!constructed) return "Contact-card style ATR (not the PC/SC contactless format).";

        int n = atr[1] & 0x0F;
        if (atr.Length < 5 + n) return "Contactless ATR, but shorter than its T0 byte says.";
        byte tck = 0;
        for (int i = 1; i < 4 + n; i++) tck ^= atr[i];
        string check = tck == atr[4 + n] ? "TCK ok" : "TCK mismatch";
        byte[] hist = atr[4..(4 + n)];

        bool storage = n >= 12 && hist[0] == 0x80 && hist[1] == 0x4F && hist[2] == 0x0C
                       && hist[3] == 0xA0 && hist[4] == 0x00 && hist[5] == 0x00 && hist[6] == 0x03 && hist[7] == 0x06;
        if (!storage)
            return $"Contactless ISO 14443-4 card (for example DESFire). Historical bytes: {Apdu.HexSpaced(hist)}. {check}.";

        string standard = hist[8] switch
        {
            0x03 => "ISO 14443 A part 3",
            0x11 => "FeliCa",
            0x0B => "ISO 15693",
            _ => $"standard byte {hist[8]:X2}"
        };
        int name = hist[9] << 8 | hist[10];
        string card = name switch
        {
            0x0001 => "MIFARE Classic 1K",
            0x0002 => "MIFARE Classic 4K",
            0x0003 => "MIFARE Ultralight family",
            0x0026 => "MIFARE Mini",
            0x003A => "MIFARE Ultralight C",
            0x0036 => "MIFARE Plus SL1 2K",
            0x0037 => "MIFARE Plus SL1 4K",
            0x0038 => "MIFARE Plus SL2 2K",
            0x0039 => "MIFARE Plus SL2 4K",
            0x0030 or 0xF004 => "Topaz / Jewel",
            0x003B or 0xF011 or 0xF012 => "FeliCa",
            _ when hist[9] == 0xFF => $"undefined card type (SAK {hist[10]:X2})",
            _ => $"card name {name:X4}"
        };
        return $"Contactless storage card: {card}, {standard}. {check}.";
    }
}

Expected result: after the reader line, each tap prints the time, the ATR in hex, one line decoding it, then the UID four ways: as returned, bytes reversed, and both as decimal numbers. A MIFARE Classic 1K card should decode as "Contactless storage card: MIFARE Classic 1K, ISO 14443 A part 3" with a 4-byte UID (7 bytes on 7-byte-UID versions); an NTAG as a storage card with a 7-byte UID starting 04; a DESFire card as an "ISO 14443-4 card" with a 7-byte UID, unless its random ID option is on. Leave the card on the reader and nothing more is printed; remove it and tap again for the next read.

If it fails: "No matching reader" lists the readers PC/SC sees; pass part of the right name, or check the reader with the PC/SC status check. "Get Data refused: status word 6A 81" means the reader does not support Get Data for that card or mode; "63 00" means the command failed, usually because the card moved. Error codes from the PC/SC calls are grouped by what to do in the C# tutorial.

A contact card sends its own ATR (Answer To Reset) when powered. A contactless card has none, so PC/SC Part 3 makes the reader build one from what it learned during card selection. That built ATR always starts 3B 8n 80 01, where n is the number of historical bytes that follow, and ends with a check byte (TCK, the XOR of every byte after 3B). The historical bytes come in two shapes:

Card groupATR built by the readerWhat the code does
Storage cards (ISO 14443-3: MIFARE Classic, Ultralight, NTAG; ISO 15693 tags on readers that support them)3B 8F 80 01 80 4F 0C A0 00 00 03 06 SS C0 C1 00 00 00 00 TCK. A0 00 00 03 06 is the PC/SC Workgroup RID, SS the standard, C0 C1 the card name.Reads SS and C0 C1 and names the card from the table below.
ISO 14443-4 cards (DESFire and other microprocessor cards)3B 8n 80 01 + the historical bytes from the card's ATS (Type A) or ATQB data (Type B) + TCK. ACS's manual gives 3B 81 80 01 80 80 for a MIFARE DESFire.Reports an ISO 14443-4 card and prints its historical bytes.

Standard and card-name bytes in ACS manuals

BytesMeaningDocumented in
SS = 03ISO 14443 A, part 3ACR122U API manual v1.4; ACR1552U reference manual v1.05
SS = 11FeliCaACR1552U reference manual v1.05
SS = 0BISO 15693 (in the ACR1552U's table of supported ATRs for ICODE and other vicinity tags)ACR1552U reference manual v1.05, section 5.3.9
00 01 / 00 02MIFARE Classic 1K / 4KBoth manuals
00 03MIFARE UltralightBoth manuals
00 26MIFARE MiniBoth manuals
00 3AMIFARE Ultralight CACR1552U reference manual
00 36 to 00 39MIFARE Plus SL1 2K, SL1 4K, SL2 2K, SL2 4KACR1552U reference manual
00 30 or F0 04Topaz and Jewel00 30 in the ACR1552U manual, F0 04 in the ACR122U manual
00 3B, or F0 11 / F0 12FeliCa00 3B in the ACR1552U manual, F0 11 (212K) and F0 12 (424K) in the ACR122U manual
FF xxUndefined card type; xx is the card's SAKBoth manuals

Two cautions. First, the two manuals use different card-name values for Topaz and FeliCa, so the code accepts both. Second, the ACR1552U manual lists some cards with a "default" and an "alternated" ATR (for example MIFARE Plus SL1 can report itself as MIFARE Classic), and NTAG is not listed separately: NTAG tags are part of the Ultralight-type family, but which card name each reader reports for them is one of BSD's hardware checks. Use the ATR to choose your next command, not as proof of the exact chip.

Existing systems store UIDs in different ways, and the reasons are explained in detail on hex, decimal and byte order. In code, four rules prevent most mismatches:

  • Keep the raw bytes as your master value, and convert only for display or for another system. Convert.ToHexString gives upper-case hex with leading zeros kept.
  • Reverse with care. "Reversed" means byte order, not character order: 04A1B2 reversed is B2A104, not 2B1A40. The code reverses the byte array before formatting.
  • Do not squeeze UIDs into int. A 4-byte UID can exceed int.MaxValue, and a 7-byte UID does not fit in 32 bits at all. The code uses BigInteger with isUnsigned: true, which works for 4, 7 and 10 bytes.
  • Watch for random IDs. A 4-byte UID starting 08 that changes on each tap is a card's random ID, not a reader fault; the code flags it. See what a UID is.

A UID is an identifier, not a security feature: any reader can read it without a key. For anything beyond recognising a card, use data protected by the card's own security, with keys you control.

The UID belongs to contactless anti-collision: the reader needs it to pick one card out of several in the field. A contact card sits alone in its slot, so ISO 7816 has no such step. What a contact reader such as the ACR39U gives you is different:

Contactless card on a PICC readerContact card in an ACR39U
IdentifierUID (4, 7 or 10 bytes), or PUPI for Type BNone at the reader level. A serial number, if the card has one, is read with that card's own commands.
ATRBuilt by the reader (PC/SC Part 3 format above)Sent by the card itself when powered (ISO 7816-3); it identifies the card's chip and protocols
FF CA 00 00 00Answered by the reader with the UID and 90 00Not a reader command for these cards; PC/SC Part 3 gives 6A 81 as the answer when there is no UID. The code does not send it.
Memory cards (SLE4428, SLE4442)Not applicableACS's ACR39x reference manual says the application must select the card type before the card is activated, and documents its own memory-card commands. That is a separate procedure, not covered here.

So on an ACR39U, the code only reports the ATR from the reader-state entry, without connecting. Whether the Smart Card service reports an ATR for SLE memory cards before the card type is selected is one of BSD's hardware checks; the page will be updated with the result.

What you seeLikely causeWhat to do
The same card is read again and againReading on every return of the wait, not only on arrivalAct only when PRESENT appears, as the loop does; remove the card to re-arm.
"The card left the field before it could be read"Card tapped and pulled away quickly, or held at the edgeHold the card flat on the centre for a moment. Expected occasionally; the loop carries on.
"Another program holds the card"QuickView, Script Tool or a second copy of your program is connectedClose it. See reader states.
Status word 6A 81Get Data not supported for this card or mode, or the SAM entry was chosenUse the PICC entry; check the card type on the model page.
A new UID on every tap, starting 08Random ID enabled on the cardUse another identifier; see UID troubleshooting.
Your UID and another system's UID do not matchByte order or decimal conversionCompare with the "reversed" and decimal lines; follow the matching steps.
ATR decodes as "contact-card style" on a contactless readerThe reader is in a mode or with a card the code does not decodePrint the ATR and compare with the reader's manual; the UID read still works if the status is 90 00.
"The reader was removed."Reader unplugged during the loopRestart, or combine the loop with reader detection to wait for it to return.

ATR layouts, standard and card-name bytes, the DESFire ATR example and the memory-card note were read on 30 Nov 2026 in ACS documents supplied with ACS SDK kits: the ACR122U API manual v1.4 (section 3.1), the ACR1552U Series reference manual v1.05 (sections 5.3.1 and 5.3.9) and the ACR39x reference manual v1.03 (section 5.3). PC/SC Part 3 (rev. 2.01.09, sections 3.1.3.2.3 and 3.2.2.1) was checked for the constructed ATR and Get Data. Microsoft's Win32 reference was checked for the PC/SC calls.

BSD Infotech is an independent ACS supplier and integrator, not the manufacturer. ACS, the ACS logo and ACS product names belong to Advanced Card Systems Ltd. MIFARE, MIFARE Classic, MIFARE DESFire, MIFARE Plus, MIFARE Ultralight, NTAG and ICODE are trademarks of NXP B.V.

Building software that reads card UIDs?

Tell us the reader, the cards and the system the UIDs must match. We build enrolment, matching and card reading in C#.