PC/SC Smart Card Programming in C#
← Back to the smart card SDK and developer centre
How do you program a smart card reader in C#? On Windows, a C# program talks to any PC/SC reader, including every ACS USB reader, through winscard.dll. You declare its functions with P/Invoke (or use a NuGet wrapper), then make the same calls in the same order: SCardEstablishContext, SCardListReaders, SCardGetStatusChange to wait for a card, SCardConnect, SCardTransmit, SCardDisconnect and SCardReleaseContext. This tutorial builds that as a .NET 10 console project with two reusable files, WinScard.cs and Pcsc.cs, and shows how to handle errors, cancel a wait and stay correct in 64-bit processes.
It is the first page of a short C# series. The same two files are used by the next guides, detecting an ACS reader in C# (reader arrival and removal) and reading a card UID in C# (tap-to-read loop, ATR decoding, contact vs contactless). Why each PC/SC call exists is explained in PC/SC architecture for developers; this page is about writing the code. BSD Infotech is an independent ACS supplier and integrator, not the manufacturer.
Two Ways In: P/Invoke or a NuGet Wrapper
.NET has no built-in class for PC/SC readers in a desktop or console program, so you either call winscard.dll yourself or use a library that does it for you. Both end up in the same Windows Smart Card service.
| Option | What it is | When it suits |
|---|---|---|
| P/Invoke to winscard.dll (this series) | About a dozen [DllImport] declarations and two structures. No package to install or update. | You want to see every call and every return code, ship no third-party code, or match your code line by line with the ACS reference manuals, which are written against the same API. |
The PCSC NuGet package (pcsc-sharp) | An open-source PC/SC wrapper by Daniel Mueller, BSD-2-Clause licence. Version 7.0.1 (June 2025) targets .NET Standard 2.0/2.1 and .NET 8. Companion packages: PCSC.Iso7816 (APDU classes) and PCSC.Reactive (card monitor events as observables). It uses the native PC/SC library of the system, so it also runs on Linux and macOS with pcsc-lite. | You prefer ready-made classes, want one code base for Windows and Linux, or want event-style card monitoring. BSD has not used it in these examples and has not tested it. |
| Windows.Devices.SmartCards (WinRT) | A Windows Runtime API for smart cards and readers. | Mainly packaged Windows apps. This series does not use it. |
Whichever you choose, the reader-specific part does not change: the bytes you send. ACS documents them in each reader's manual, and BSD summarises them on the ACR1252U, ACR1552U and ACR122U SDK pages. Not sure whether you need an SDK at all? See smart card reader SDK vs driver.
Set Up a .NET 10 Console Project
- Install the driver and check the reader first. Install the ACS driver for your model (driver guide) and confirm that PC/SC lists the reader (PC/SC status check). Code cannot fix a reader that Windows does not offer to programs.
- Install a .NET SDK. The .NET 10 SDK, or a newer SDK: a newer SDK still builds projects that target
net10.0. Check withdotnet --list-sdks. - Create the project. Run
dotnet new console -n PcscDemo. With the .NET 10 SDK the template already targetsnet10.0, so the project file needs no changes. - Add the two shared files. Save
WinScard.csandPcsc.csnext toProgram.cs. Every.csfile in the project folder is compiled, so nothing else is needed. - Replace Program.cs with the program below, then run
dotnet build. Expected result:Build succeededwith 0 errors. - Run it with
dotnet run, ordotnet run -- ACR1252to choose a reader by part of its name.
The finished project file looks like this. Nothing else is required: no NuGet packages, no unsafe code, no Windows-specific target framework.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
Step 1: The P/Invoke Declarations (WinScard.cs)
This file declares the Windows PC/SC functions, the two structures they need and the constants the series uses. It contains no logic. Three rules decide whether P/Invoke code like this works:
| C type in winscard.h | C# type | Why |
|---|---|---|
SCARDCONTEXT, SCARDHANDLE | IntPtr | Pointer-sized: 4 bytes in a 32-bit process, 8 in a 64-bit one. An int works by luck in 32-bit code and breaks in 64-bit code. |
DWORD | uint | Always 32-bit on Windows. |
LONG (return codes) | int | Windows LONG is 32-bit even in 64-bit processes. C# long is 64-bit, so it is the wrong type here. |
LPCWSTR, multi-string buffers | string, char[] with CharSet.Unicode | Call the ...W (Unicode) functions explicitly. Lengths are in characters, not bytes. |
SCARD_READERSTATE | sequential struct with a 36-byte rgbAtr | Microsoft defines rgbAtr[36]. The marshaller handles the padding for 32-bit and 64-bit layouts. |
Language: C# 14 on .NET 10, Windows only. Prerequisites: none beyond the project above.
Compiled by BSD; not yet tested on a reader. Built with dotnet build for net10.0 on 1 Dec 2026 (0 warnings, 0 errors), as part of the three example programs in this series. BSD plans to run the series on the ACR1252U, ACR1552U, ACR122U and ACR39U; this note will then name the reader, card and Windows version tested.
// WinScard.cs: P/Invoke declarations for the Windows PC/SC API (winscard.dll).
// C# 14, .NET 10, Windows only. Shared by the BSD Infotech C# PC/SC examples.
// Compiled by BSD; not yet tested on a reader.
using System;
using System.Runtime.InteropServices;
namespace Bsd.Pcsc;
public static class WinScard
{
// Scope, share modes, protocols and dispositions (values from winscard.h).
public const uint SCARD_SCOPE_USER = 0;
public const uint SCARD_SHARE_EXCLUSIVE = 1, SCARD_SHARE_SHARED = 2, SCARD_SHARE_DIRECT = 3;
public const uint SCARD_PROTOCOL_UNDEFINED = 0, SCARD_PROTOCOL_T0 = 1, SCARD_PROTOCOL_T1 = 2;
public const uint SCARD_LEAVE_CARD = 0, SCARD_RESET_CARD = 1, SCARD_UNPOWER_CARD = 2;
public const uint INFINITE = 0xFFFFFFFF;
// Reader state flags (SCARD_READERSTATE.dwCurrentState / dwEventState).
public const uint SCARD_STATE_UNAWARE = 0x0000, SCARD_STATE_IGNORE = 0x0001, SCARD_STATE_CHANGED = 0x0002,
SCARD_STATE_UNKNOWN = 0x0004, SCARD_STATE_UNAVAILABLE = 0x0008, SCARD_STATE_EMPTY = 0x0010,
SCARD_STATE_PRESENT = 0x0020, SCARD_STATE_ATRMATCH = 0x0040, SCARD_STATE_EXCLUSIVE = 0x0080,
SCARD_STATE_INUSE = 0x0100, SCARD_STATE_MUTE = 0x0200, SCARD_STATE_UNPOWERED = 0x0400;
// Special reader name: SCardGetStatusChange returns when a reader is plugged in.
public const string PnpNotification = @"\\?PnP?\Notification";
// Return codes used by the examples (Microsoft: Smart Card Return Values).
public const int SCARD_S_SUCCESS = 0;
public const int SCARD_E_CANCELLED = unchecked((int)0x80100002);
public const int SCARD_E_INVALID_HANDLE = unchecked((int)0x80100003);
public const int SCARD_E_INSUFFICIENT_BUFFER = unchecked((int)0x80100008);
public const int SCARD_E_UNKNOWN_READER = unchecked((int)0x80100009);
public const int SCARD_E_TIMEOUT = unchecked((int)0x8010000A);
public const int SCARD_E_SHARING_VIOLATION = unchecked((int)0x8010000B);
public const int SCARD_E_NO_SMARTCARD = unchecked((int)0x8010000C);
public const int SCARD_E_PROTO_MISMATCH = unchecked((int)0x8010000F);
public const int SCARD_E_NOT_READY = unchecked((int)0x80100010);
public const int SCARD_F_COMM_ERROR = unchecked((int)0x80100013);
public const int SCARD_E_READER_UNAVAILABLE = unchecked((int)0x80100017);
public const int SCARD_E_NO_SERVICE = unchecked((int)0x8010001D);
public const int SCARD_E_SERVICE_STOPPED = unchecked((int)0x8010001E);
public const int SCARD_E_NO_READERS_AVAILABLE = unchecked((int)0x8010002E);
public const int SCARD_E_COMM_DATA_LOST = unchecked((int)0x8010002F);
public const int SCARD_W_UNRESPONSIVE_CARD = unchecked((int)0x80100066);
public const int SCARD_W_UNPOWERED_CARD = unchecked((int)0x80100067);
public const int SCARD_W_RESET_CARD = unchecked((int)0x80100068);
public const int SCARD_W_REMOVED_CARD = unchecked((int)0x80100069);
public const int ERROR_BROKEN_PIPE = 0x00000109;
// Handles (SCARDCONTEXT, SCARDHANDLE) are pointer-sized: IntPtr, never int.
// DWORD is uint and LONG is int on both 32-bit and 64-bit Windows.
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct SCARD_READERSTATE
{
public string szReader;
public IntPtr pvUserData;
public uint dwCurrentState;
public uint dwEventState;
public uint cbAtr;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 36)]
public byte[] rgbAtr;
}
[StructLayout(LayoutKind.Sequential)]
public struct SCARD_IO_REQUEST
{
public uint dwProtocol;
public uint cbPciLength;
}
[DllImport("winscard.dll")]
public static extern int SCardEstablishContext(uint scope, IntPtr reserved1, IntPtr reserved2, out IntPtr context);
[DllImport("winscard.dll")]
public static extern int SCardReleaseContext(IntPtr context);
[DllImport("winscard.dll")]
public static extern int SCardCancel(IntPtr context);
[DllImport("winscard.dll", EntryPoint = "SCardListReadersW", CharSet = CharSet.Unicode)]
public static extern int SCardListReaders(IntPtr context, string? groups, char[]? readers, ref uint chars);
[DllImport("winscard.dll", EntryPoint = "SCardGetStatusChangeW", CharSet = CharSet.Unicode)]
public static extern int SCardGetStatusChange(IntPtr context, uint timeoutMs,
[In, Out] SCARD_READERSTATE[] readerStates, uint count);
[DllImport("winscard.dll", EntryPoint = "SCardConnectW", CharSet = CharSet.Unicode)]
public static extern int SCardConnect(IntPtr context, string reader, uint shareMode, uint preferredProtocols,
out IntPtr card, out uint activeProtocol);
[DllImport("winscard.dll")]
public static extern int SCardDisconnect(IntPtr card, uint disposition);
[DllImport("winscard.dll", EntryPoint = "SCardStatusW", CharSet = CharSet.Unicode)]
public static extern int SCardStatus(IntPtr card, char[] readerNames, ref uint readerChars,
out uint state, out uint protocol, byte[] atr, ref uint atrLength);
[DllImport("winscard.dll")]
public static extern int SCardTransmit(IntPtr card, ref SCARD_IO_REQUEST sendPci, byte[] sendBuffer,
uint sendLength, IntPtr recvPci, byte[] recvBuffer, ref uint recvLength);
}
The state flags and return codes are the values in Microsoft's winscard.h and its Smart Card Return Values list. Only the codes the series reacts to are declared; add others from that list as you need them.
Step 2: A Small Disposable Layer (Pcsc.cs)
Calling the raw functions from every part of an application leads to two common bugs: a handle that is never released after an error, and a return code that nobody checks. Pcsc.cs fixes both with three small types:
PcscContextowns the context. Its constructor callsSCardEstablishContext,DisposecallsSCardReleaseContext, and it offersListReaders,WaitForChange(with aCancellationToken),CancelandConnect.CardConnectionowns a card handle.Transmitsends one APDU,Statusreturns the card state, protocol and ATR, andDisposedisconnects withSCARD_LEAVE_CARD, so another program's session with the card is not reset.PcscExceptioncarries the failing call and its return code, with the code's name, for exampleSCardConnect failed: 0x8010000C (SCARD_E_NO_SMARTCARD).
Because both handle types are IDisposable, a using declaration guarantees the clean-up order (disconnect, then release) even when an exception is thrown halfway.
Compiled by BSD; not yet tested on a reader. Same build as above. It is a teaching layer, not a full library: it has no transactions, no SCardControl and no SCardReconnect. The firmware version guide shows SCardControl, and PC/SC architecture explains transactions and dispositions.
// Pcsc.cs: a small, disposable C# layer over WinScard.cs.
// C# 14, .NET 10, Windows only. Shared by the BSD Infotech C# PC/SC examples.
// Compiled by BSD; not yet tested on a reader.
using System;
using System.Collections.Generic;
using System.Threading;
namespace Bsd.Pcsc;
/// <summary>A failed PC/SC call, with the call name and the Windows return code.</summary>
public sealed class PcscException(string call, int code)
: Exception($"{call} failed: 0x{code:X8} ({PcscErrors.Name(code)})")
{
public int Code { get; } = code;
}
public static class PcscErrors
{
public static string Name(int code) => code switch
{
WinScard.SCARD_E_CANCELLED => "SCARD_E_CANCELLED",
WinScard.SCARD_E_INVALID_HANDLE => "SCARD_E_INVALID_HANDLE",
WinScard.SCARD_E_INSUFFICIENT_BUFFER => "SCARD_E_INSUFFICIENT_BUFFER",
WinScard.SCARD_E_UNKNOWN_READER => "SCARD_E_UNKNOWN_READER",
WinScard.SCARD_E_TIMEOUT => "SCARD_E_TIMEOUT",
WinScard.SCARD_E_SHARING_VIOLATION => "SCARD_E_SHARING_VIOLATION",
WinScard.SCARD_E_NO_SMARTCARD => "SCARD_E_NO_SMARTCARD",
WinScard.SCARD_E_PROTO_MISMATCH => "SCARD_E_PROTO_MISMATCH",
WinScard.SCARD_E_NOT_READY => "SCARD_E_NOT_READY",
WinScard.SCARD_F_COMM_ERROR => "SCARD_F_COMM_ERROR",
WinScard.SCARD_E_READER_UNAVAILABLE => "SCARD_E_READER_UNAVAILABLE",
WinScard.SCARD_E_NO_SERVICE => "SCARD_E_NO_SERVICE",
WinScard.SCARD_E_SERVICE_STOPPED => "SCARD_E_SERVICE_STOPPED",
WinScard.SCARD_E_NO_READERS_AVAILABLE => "SCARD_E_NO_READERS_AVAILABLE",
WinScard.SCARD_E_COMM_DATA_LOST => "SCARD_E_COMM_DATA_LOST",
WinScard.SCARD_W_UNRESPONSIVE_CARD => "SCARD_W_UNRESPONSIVE_CARD",
WinScard.SCARD_W_UNPOWERED_CARD => "SCARD_W_UNPOWERED_CARD",
WinScard.SCARD_W_RESET_CARD => "SCARD_W_RESET_CARD",
WinScard.SCARD_W_REMOVED_CARD => "SCARD_W_REMOVED_CARD",
WinScard.ERROR_BROKEN_PIPE => "ERROR_BROKEN_PIPE",
_ => "see Microsoft Smart Card Return Values"
};
/// <summary>True for codes after which the context must be released and established again.</summary>
public static bool ContextLost(int code) =>
code is WinScard.SCARD_E_NO_SERVICE or WinScard.SCARD_E_SERVICE_STOPPED or WinScard.SCARD_E_INVALID_HANDLE;
}
/// <summary>One session with the Smart Card service (SCardEstablishContext ... SCardReleaseContext).
/// Use a context from one thread only; the one call made from another thread is Cancel().</summary>
public sealed class PcscContext : IDisposable
{
private IntPtr _handle;
public PcscContext()
{
int rc = WinScard.SCardEstablishContext(WinScard.SCARD_SCOPE_USER, IntPtr.Zero, IntPtr.Zero, out _handle);
if (rc != WinScard.SCARD_S_SUCCESS) throw new PcscException("SCardEstablishContext", rc);
}
/// <summary>All PC/SC reader names. Returns an empty array when no reader is connected.</summary>
public string[] ListReaders()
{
uint chars = 0;
int rc = WinScard.SCardListReaders(_handle, null, null, ref chars);
if (rc == WinScard.SCARD_E_NO_READERS_AVAILABLE) return [];
if (rc != WinScard.SCARD_S_SUCCESS) throw new PcscException("SCardListReaders", rc);
var buffer = new char[chars];
rc = WinScard.SCardListReaders(_handle, null, buffer, ref chars);
if (rc == WinScard.SCARD_E_NO_READERS_AVAILABLE) return []; // the last reader left between the two calls
if (rc != WinScard.SCARD_S_SUCCESS) throw new PcscException("SCardListReaders", rc);
return new string(buffer, 0, (int)chars).Split('\0', StringSplitOptions.RemoveEmptyEntries);
}
/// <summary>Calls SCardGetStatusChange. Returns false on time-out.
/// Cancelling the token calls SCardCancel, which ends the wait with SCARD_E_CANCELLED.</summary>
public bool WaitForChange(WinScard.SCARD_READERSTATE[] states, uint timeoutMs, CancellationToken token)
{
token.ThrowIfCancellationRequested();
using (token.Register(Cancel))
{
int rc = WinScard.SCardGetStatusChange(_handle, timeoutMs, states, (uint)states.Length);
if (rc == WinScard.SCARD_S_SUCCESS) return true;
if (rc == WinScard.SCARD_E_TIMEOUT) return false;
if (rc == WinScard.SCARD_E_CANCELLED) throw new OperationCanceledException(token);
throw new PcscException("SCardGetStatusChange", rc);
}
}
/// <summary>Ends a blocking SCardGetStatusChange on this context. Safe to call from another thread.</summary>
public void Cancel()
{
if (_handle != IntPtr.Zero) WinScard.SCardCancel(_handle);
}
/// <summary>Connects to the card in a reader. Shared mode needs a card on the reader.</summary>
public CardConnection Connect(string reader, uint shareMode = WinScard.SCARD_SHARE_SHARED,
uint protocols = WinScard.SCARD_PROTOCOL_T0 | WinScard.SCARD_PROTOCOL_T1)
{
int rc = WinScard.SCardConnect(_handle, reader, shareMode, protocols, out IntPtr card, out uint active);
if (rc != WinScard.SCARD_S_SUCCESS) throw new PcscException("SCardConnect", rc);
return new CardConnection(card, active);
}
public void Dispose()
{
if (_handle == IntPtr.Zero) return;
WinScard.SCardReleaseContext(_handle);
_handle = IntPtr.Zero;
}
/// <summary>A reader-state entry ready for SCardGetStatusChange (all members zero except the name).</summary>
public static WinScard.SCARD_READERSTATE NewState(string reader) =>
new() { szReader = reader, rgbAtr = new byte[36] };
/// <summary>After a wait, make the reported state the new "current" state (minus the CHANGED bit).</summary>
public static void Acknowledge(WinScard.SCARD_READERSTATE[] states)
{
for (int i = 0; i < states.Length; i++)
states[i].dwCurrentState = states[i].dwEventState & ~WinScard.SCARD_STATE_CHANGED;
}
public static byte[] Atr(in WinScard.SCARD_READERSTATE s) =>
s.cbAtr is > 0 and <= 36 ? s.rgbAtr[..(int)s.cbAtr] : [];
public static string Describe(uint state)
{
var names = new List<string>();
if ((state & WinScard.SCARD_STATE_UNKNOWN) != 0) names.Add("UNKNOWN");
if ((state & WinScard.SCARD_STATE_UNAVAILABLE) != 0) names.Add("UNAVAILABLE");
if ((state & WinScard.SCARD_STATE_EMPTY) != 0) names.Add("EMPTY");
if ((state & WinScard.SCARD_STATE_PRESENT) != 0) names.Add("PRESENT");
if ((state & WinScard.SCARD_STATE_EXCLUSIVE) != 0) names.Add("EXCLUSIVE");
if ((state & WinScard.SCARD_STATE_INUSE) != 0) names.Add("INUSE");
if ((state & WinScard.SCARD_STATE_MUTE) != 0) names.Add("MUTE");
if ((state & WinScard.SCARD_STATE_UNPOWERED) != 0) names.Add("UNPOWERED");
return names.Count == 0 ? "-" : string.Join("|", names);
}
}
/// <summary>An open connection to a card (SCardConnect ... SCardDisconnect).</summary>
public sealed class CardConnection : IDisposable
{
private IntPtr _card;
internal CardConnection(IntPtr card, uint protocol) { _card = card; Protocol = protocol; }
/// <summary>The protocol Windows negotiated: SCARD_PROTOCOL_T0 or SCARD_PROTOCOL_T1.</summary>
public uint Protocol { get; }
/// <summary>Sends one APDU with SCardTransmit and returns the reply, status word included.</summary>
public byte[] Transmit(byte[] apdu)
{
// Protocol header: two DWORDs, so 8 bytes in both 32-bit and 64-bit processes.
var pci = new WinScard.SCARD_IO_REQUEST { dwProtocol = Protocol, cbPciLength = 8 };
var reply = new byte[258]; // 256 data bytes + SW1 SW2
uint length = (uint)reply.Length;
int rc = WinScard.SCardTransmit(_card, ref pci, apdu, (uint)apdu.Length, IntPtr.Zero, reply, ref length);
if (rc != WinScard.SCARD_S_SUCCESS) throw new PcscException("SCardTransmit", rc);
return reply[..(int)length];
}
/// <summary>SCardStatus: card state (SCARD_ABSENT=1 ... SCARD_SPECIFIC=6), protocol and ATR.</summary>
public (uint State, uint Protocol, byte[] Atr) Status()
{
var names = new char[256];
uint chars = (uint)names.Length;
var atr = new byte[36];
uint atrLength = (uint)atr.Length;
int rc = WinScard.SCardStatus(_card, names, ref chars, out uint state, out uint protocol, atr, ref atrLength);
if (rc != WinScard.SCARD_S_SUCCESS) throw new PcscException("SCardStatus", rc);
return (state, protocol, atr[..(int)atrLength]);
}
/// <summary>SCardDisconnect with SCARD_LEAVE_CARD, so other programs' sessions are not reset.</summary>
public void Dispose()
{
if (_card == IntPtr.Zero) return;
WinScard.SCardDisconnect(_card, WinScard.SCARD_LEAVE_CARD);
_card = IntPtr.Zero;
}
}
public static class Apdu
{
/// <summary>PC/SC Get Data, UID of a contactless card: FF CA 00 00 00.</summary>
public static readonly byte[] GetUid = [0xFF, 0xCA, 0x00, 0x00, 0x00];
public static bool IsSuccess(byte[] reply) => reply.Length >= 2 && reply[^2] == 0x90 && reply[^1] == 0x00;
public static byte[] Data(byte[] reply) => reply.Length >= 2 ? reply[..^2] : [];
public static string StatusWord(byte[] reply) => reply.Length >= 2 ? $"{reply[^2]:X2} {reply[^1]:X2}" : "none";
public static string Hex(byte[] bytes) => Convert.ToHexString(bytes);
public static string HexSpaced(byte[] bytes) => string.Join(" ", Array.ConvertAll(bytes, b => b.ToString("X2")));
}
Two helpers matter for event handling. NewState creates a reader-state entry with every member zero except the name, which Microsoft requires (otherwise SCardGetStatusChange can fail with remote readers). Acknowledge copies the state Windows reported into the state your program believes, so the next wait returns only on a new change.
Step 3: Context, Readers, Connect, Transmit, Disconnect
Language: C# 14 on .NET 10, Windows only. Prerequisites: the project from the setup with WinScard.cs and Pcsc.cs; an ACS reader with its driver; for the last step, a contactless card such as MIFARE Classic 1K or NTAG on an ACR1252U, ACR1552U or ACR122U.
The program walks through the whole sequence once. It is read-only: the only command it sends is Get Data (FF CA 00 00 00), and only to a contactless (PICC) reader. On a contact reader such as the ACR39U it stops after reading the ATR.
Compiled by BSD; not yet tested on a reader. Built for net10.0 on 1 Dec 2026 with 0 warnings and 0 errors. It has not been run with an ACS reader and a card yet.
// Day 35: the PC/SC call sequence in C#. 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: lists readers, waits for a card, reads the ATR and, on a contactless (PICC) reader,
// sends Get Data FF CA 00 00 00. It writes nothing to the card or the reader.
using System;
using System.Linq;
using System.Threading;
using Bsd.Pcsc;
using var cts = new CancellationTokenSource();
Console.CancelKeyPress += (_, e) => { e.Cancel = true; cts.Cancel(); }; // Ctrl+C ends the wait cleanly
try
{
// 1. Context: a session with the Smart Card service.
using var pcsc = new PcscContext();
// 2. Readers: pick by part of the name (argument), never by position.
string[] readers = pcsc.ListReaders();
if (readers.Length == 0) { Console.WriteLine("No PC/SC readers. Check the driver and the Smart Card service."); return 1; }
for (int i = 0; i < readers.Length; i++) Console.WriteLine($"Reader {i}: {readers[i]}");
string filter = args.Length > 0 ? args[0] : "PICC";
string reader = readers.FirstOrDefault(r => r.Contains(filter, StringComparison.OrdinalIgnoreCase)) ?? readers[0];
Console.WriteLine($"Using: {reader}");
// 3. Wait (up to 15 s) until a card is present. dwCurrentState starts as UNAWARE, so the first call returns at once.
var state = new[] { PcscContext.NewState(reader) };
pcsc.WaitForChange(state, 0, cts.Token);
while ((state[0].dwEventState & WinScard.SCARD_STATE_PRESENT) == 0)
{
Console.WriteLine("Place a card on the reader (15 s; Ctrl+C to stop)...");
PcscContext.Acknowledge(state);
if (!pcsc.WaitForChange(state, 15_000, cts.Token)) { Console.WriteLine("No card within 15 s."); return 2; }
}
// 4. Connect in shared mode, accepting T=0 or T=1. Windows reports the protocol it chose.
using var card = pcsc.Connect(reader);
var (cardState, protocol, atr) = card.Status();
Console.WriteLine($"Protocol: {(protocol == WinScard.SCARD_PROTOCOL_T1 ? "T=1" : protocol == WinScard.SCARD_PROTOCOL_T0 ? "T=0" : protocol.ToString())}, card state {cardState}");
Console.WriteLine($"ATR: {Apdu.HexSpaced(atr)}");
// 5. Transmit: one read-only command, on contactless readers only.
if (reader.Contains("PICC", StringComparison.OrdinalIgnoreCase))
{
byte[] reply = card.Transmit(Apdu.GetUid);
Console.WriteLine(Apdu.IsSuccess(reply)
? $"UID: {Apdu.Hex(Apdu.Data(reply))} (status 90 00)"
: $"Get Data refused, status word {Apdu.StatusWord(reply)}");
}
else
{
Console.WriteLine("Not a PICC (contactless) reader: no command sent.");
}
return 0; // 6. 'using' disconnects (SCARD_LEAVE_CARD) and releases the context, also after an exception.
}
catch (OperationCanceledException)
{
Console.WriteLine("Stopped.");
return 130;
}
catch (PcscException ex)
{
Console.WriteLine(ex.Message);
return 1;
}
Expected result: one Reader n: line per PC/SC reader (an ACR1252U shows two, its contactless PICC entry and its SAM slot), then Using: with the PICC entry. With a card on the reader you see Protocol: T=1 or T=0, the ATR in hex, and UID: followed by the card's UID. Without a card the program asks you to place one and gives up after 15 seconds. The exit code tells a calling script what happened: 0 done, 1 PC/SC error or no reader, 2 no card, 130 stopped with Ctrl+C.
If it fails: the message names the call and the code, for example SCardEstablishContext failed: 0x8010001D (SCARD_E_NO_SERVICE). The meaning of every common code is in the PC/SC error code table; what your program should do about it is below. A status word other than 90 00 after Get Data is the card's or reader's answer, not a PC/SC error: see what status words mean.
From here to your own commands
Replace Apdu.GetUid with your own command bytes and keep everything else. How to send APDU commands explains how to build them, including the 61 xx (GET RESPONSE) and 6C xx cases that a longer exchange must handle. Commands to the reader itself (LED, buzzer, firmware) use SCardControl instead of SCardTransmit; see SCardTransmit vs SCardControl.
Error Handling: What Your Code Should Do
Every exchange has two results, and they need different handling. First the PC/SC return code of the call: if it is not 0, the command did not complete. Only then the status word, the last two bytes of a successful SCardTransmit reply. PcscException covers the first; Apdu.IsSuccess and Apdu.StatusWord cover the second.
For the return codes, the useful question in code is not "what does it mean" but "what do I do next". BSD groups them like this:
| Group | Codes | What the program should do |
|---|---|---|
| Normal, not an error | SCARD_E_TIMEOUT 0x8010000A, SCARD_E_CANCELLED 0x80100002 | A wait ended without a change, or your own code cancelled it. WaitForChange returns false or throws OperationCanceledException. |
| The card went away | SCARD_W_REMOVED_CARD 0x80100069, SCARD_E_NO_SMARTCARD 0x8010000C | Dispose the connection, tell the user to hold the card still, and wait for the next card. Do not retry in a tight loop. |
| Someone else has the card | SCARD_E_SHARING_VIOLATION 0x8010000B, SCARD_W_RESET_CARD 0x80100068 | Another program holds or reset the card. Show which tool to close; after a reset, connect again. |
| The reader went away | SCARD_E_READER_UNAVAILABLE 0x80100017, SCARD_E_UNKNOWN_READER 0x80100009 | List the readers again and pick the reader by name. Detecting an ACS reader in C# shows how to wait for it to come back. |
| The context is dead | SCARD_E_NO_SERVICE 0x8010001D, SCARD_E_SERVICE_STOPPED 0x8010001E, SCARD_E_INVALID_HANDLE 0x80100003 | Release everything, establish a new context, list readers again. PcscErrors.ContextLost tests for these three. |
| Fix the code or setup | SCARD_E_PROTO_MISMATCH 0x8010000F, SCARD_E_INSUFFICIENT_BUFFER 0x80100008, ERROR_BROKEN_PIPE 0x00000109 | Request both T=0 and T=1; ask for the buffer size first; in a Remote Desktop session, check smart card redirection. |
Some tools print these codes as negative decimal numbers (0x8010000C is -2146435060), because the value is a signed 32-bit LONG. In C#, write them as unchecked((int)0x8010000C), as WinScard.cs does, and print them with {rc:X8}.
Threads, Waiting and Cancellation
SCardGetStatusChange blocks until a reader's state changes or the time-out ends. With INFINITE it can block for hours. That is the right way to wait for a card (no polling loop, no CPU use), but it shapes how a real application is built:
- Never block the UI thread. In a WinForms or WPF application, run the waiting loop on its own thread (
Task.Runor a dedicatedThread) and pass results back to the UI withControl.Invokeor the WPFDispatcher. - One context per thread. Give the waiting thread its own
PcscContext. Microsoft's reference does not describe sharing a context between threads; the pcsc-lite documentation says each thread shall use its own context, except forSCardCancel. Following that rule keeps the code correct on both. - Cancel with SCardCancel. Microsoft describes
SCardCancelas the way to force an outstandingSCardGetStatusChangeto end; the wait then returnsSCARD_E_CANCELLED. Call it with the same context the wait uses. InPcsc.cs, aCancellationTokendoes this for you:token.Register(Cancel)callsSCardCancelfrom whichever thread cancels the token. - Shut down in order. Cancel the token, wait for the worker thread to finish, then dispose the context. Releasing a context while another thread is still inside a call on it is a race.
- Prefer a time-out you can live with. If your application has no cancellation path, use a finite time-out (for example 1 000 ms) and loop, so a shutdown is never stuck behind an infinite wait.
The console programs in this series use the same pattern: Ctrl+C sets e.Cancel = true (so the process does not die mid-call) and cancels the token, the wait ends, and the using declarations disconnect and release in order. The reader detection guide uses it for a watcher that runs until stopped.
32-bit, 64-bit and Platform Notes
- No separate build is needed. A .NET 10 console project builds as "Any CPU" by default and runs in a 64-bit process on 64-bit Windows. Windows ships
winscard.dllfor both 64-bit and 32-bit processes, and[DllImport("winscard.dll")]loads the right one. - Structure sizes differ.
SCARD_READERSTATEholds two pointers, so it is larger in a 64-bit process. Let the marshaller lay it out from the declaration; never hard-code its size.SCARD_IO_REQUESTholds twoDWORDs and is 8 bytes in both, which is whyPcsc.cscan setcbPciLength = 8. - Old code ported from 32-bit samples often stores handles in
intor declares return codes aslong. Both compile and then fail at run time in a 64-bit process. Check them first when an old sample "works in x86 only". - Forcing 32-bit (
<PlatformTarget>x86</PlatformTarget>) is only needed when the same process loads a 32-bit-only DLL, such as an old vendor library. - Windows only. The code calls
winscard.dllby name. On Linux or macOS the PC/SC library and some types differ (pcsc-lite differences); a cross-platform project is a good reason to look at the NuGet wrapper above. - Not checked by BSD: Windows on Arm (ARM64) and ACS driver support for it.
The C# Series and Related Code
Detect an ACS reader in C#
Find ACS readers by name, tell the contactless, SAM and contact entries apart, and react when a reader is plugged in or removed.
Uses WinScard.cs and Pcsc.cs from this page
Read a card UID in C#
A tap-to-read loop: wait for each card, decode its ATR, read the UID with FF CA 00 00 00, and handle contact cards correctly.
Uses WinScard.cs and Pcsc.cs from this page
PC/SC status check
A single-file, read-only program that lists readers and their states without connecting. Good for support staff.
Single file, no shared code
Reader firmware version
The SCardControl route: escape commands to the reader in direct mode, with no card.
ACR1252U, ACR1552U, ACR122U
Troubleshooting C# PC/SC Code
| What you see | Likely cause | What to do |
|---|---|---|
The new project's <TargetFramework> is not net10.0 | The project was created with an older .NET SDK; the template uses its own SDK's version | Install the .NET 10 SDK (check with dotnet --list-sdks) and create the project again. |
DllNotFoundException: winscard.dll | Running on Linux or macOS, or in a container without the Windows smart card stack | Run on Windows 10 or 11, or switch to a cross-platform wrapper. |
| Reader names come out garbled or cut after one letter | An ANSI declaration, or a byte buffer read as characters | Use the W entry points with CharSet.Unicode and a char[] buffer, as in WinScard.cs. |
SCardEstablishContext returns 0x8010001D | Smart Card service not running | Plug in the reader and check the service (service check). |
| The program never returns | An INFINITE wait with no card and no cancellation path, or a wait on the UI thread | Use the cancellation pattern, or a finite time-out. |
| Works for hours, then every call returns 0x80100003 or 0x8010001E | The Smart Card service restarted; old handles are invalid | Catch PcscErrors.ContextLost codes and build a new context. |
SCardConnect returns 0x8010000B | Another program (QuickView, Script Tool, a second copy of yours) has the card | Close it. See "another program is using the reader". |
SCardTransmit returns an error immediately | Protocol header does not match the active protocol | Use the protocol SCardConnect returned, as CardConnection does. |
| Old sample works as x86 but crashes as x64 | Handles stored as int, or long return codes | See 64-bit notes. |
Sources
Function signatures, structure layouts, state flags, return codes and the behaviour of SCardCancel and \\?PnP?\Notification were checked in Microsoft's Win32 reference on 30 Nov 2026. The thread rule was checked in the pcsc-lite API documentation, and the NuGet package details on nuget.org, on the same day. The code was written by BSD Infotech.
- SCardEstablishContext, SCardGetStatusChange, SCardCancel, SCardStatus and SCARD_READERSTATE (Microsoft Win32 reference)
- Microsoft: Smart Card Return Values
- pcsc-lite API documentation (threads and contexts, SCardCancel)
- PCSC package on nuget.org and its source repository
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. Windows and .NET are trademarks of Microsoft Corporation.
