How to Build an NFC Reader Application in .NET with an ACS Reader
← Back to PC/SC smart card programming in C#
How do you build an NFC reader application in .NET? Put all PC/SC work on one background thread that owns its own context. That thread waits for a reader, then for each card tap with SCardGetStatusChange, reads the ATR and the UID (FF CA 00 00 00), and passes each result to the window through Progress<T>. The window only displays results and never calls winscard.dll. Closing the window cancels the wait with SCardCancel. If the reader is unplugged, the thread goes back to waiting for one. Publish the app self-contained, and install the ACS driver on each PC.
This guide builds that application as a small Windows Forms program for .NET 10: reader status, tap-to-read, UID, ATR and card type, a timestamped scan log and CSV export. It works with ACS contactless readers such as the ACR1252U, ACR1552U and ACR122U. The code is shown in full below.
Which page do you need? The C# series covers one step per console program: PC/SC programming in C# (the shared WinScard.cs and Pcsc.cs files), detecting ACS readers and reading a card UID. This page puts those steps together into a desktop application with a window, a worker thread, a log and an installer-free package. If you only need the UID typed into an existing program, keyboard emulation may be enough, with no code at all. If you want to make existing software work with a reader, see connecting an ACS reader to a Windows application.
What the Application Does
- Reader status across the top of the window: "Starting", "No reader", "Ready. Tap a card." or "Card on the reader", shown in a different colour for each state. It also shows the name of the reader in use.
- Automatic reader choice: the first ACS contactless (PICC) entry, or any PICC entry if no ACS reader is connected. SAM and contact (ICC) entries are skipped. Matching ACS reader names explains why the code matches on
PICC. - One read per tap: UID in hex, the ATR and a card type decoded from the ATR (for example "MIFARE Classic 1K" or "ISO 14443-4 card (e.g. DESFire)"). A card left on the reader is read once, not again and again.
- Scan log with date and time, UID, card type, result, reader and ATR, newest first. Failed reads go in the log too, with the reason: card removed too early, card in use by another program, or no answer from the card.
- CSV export of the whole log, and a button to clear it.
- Unplug and plug back in: the app notices when the reader is removed, waits, and starts reading again when a reader returns. No restart is needed. The same applies when the Windows Smart Card service stops and starts.
It is read-only. The only card command is Get Data FF CA 00 00 00; the ATR comes from Windows without a command. It loads no keys, reads no card memory and writes nothing. For card data, add the commands from sending APDU commands to the reader thread once the basics work.
Why Windows Forms rather than WPF
Both work, and the reader code is the same for both. BSD chose Windows Forms for this sample for three reasons. The whole window can be built in about 130 lines of C#, with no XAML and no designer file, so it can be shown in full here. It is what many in-house attendance and canteen tools are already written in. It also starts with less code for a single-window tool. Choose WPF if your application needs data binding, MVVM, styling or several views. ReaderWorker.cs moves across unchanged, because Progress<T> posts to the WPF Dispatcher the same way it posts to the Windows Forms message loop.
| Point | Windows Forms (this sample) | WPF |
|---|---|---|
| Project setting | <UseWindowsForms>true</UseWindowsForms> | <UseWPF>true</UseWPF> |
| Back to the UI thread | Progress<T>, or Control.BeginInvoke | Progress<T>, or Dispatcher.BeginInvoke |
| UI code for this app | One C# file | XAML file + code-behind or view model |
| Best for | Single-window tools, kiosks, quick in-house apps | Larger apps with bound data and custom styling |
Architecture: UI Thread and Reader Thread
SCardGetStatusChange blocks until something changes, which can be hours. A desktop app must therefore do its waiting somewhere other than the UI thread. The threading rules are explained in the C# tutorial; here is how this app applies them:
UI thread (MainForm) Reader thread (ReaderWorker, its own PC/SC context)
-------------------- ---------------------------------------------------
Shown -> worker.Start() ------------> establish context
loop: list readers, pick the PICC entry
none? wait on \\?PnP?\Notification (5 s safety net)
found? wait for card (INFINITE)
card arrives -> ATR, connect, FF CA, disconnect
OnReaderUpdate(update) <-- Progress.Report -- report status / scan record
update labels, add log row reader removed -> back to "list readers"
service stopped -> new context after 2 s
FormClosing -> worker.Stop()
token.Cancel() -> SCardCancel --> wait ends with SCARD_E_CANCELLED -> thread exits
Task.Wait(3 s) context released (using)
- One owner for the PC/SC context. Only the reader thread creates, uses and releases its
PcscContext. The one call made from another thread isSCardCancel, which is the documented way to end a wait. It runs through the cancellation token thatPcsc.csregisters. - Post, never block.
Progress<T>is created in the form's constructor, so it captures the UI thread's synchronization context.Report()posts to it and returns at once. This matters at shutdown: the UI thread waits for the reader thread inStop(). If the reader thread used a blockingControl.Invokeat that moment, each thread would wait for the other forever. Posting cannot deadlock. - A dedicated thread.
TaskCreationOptions.LongRunninggives the loop its own thread instead of holding a thread-pool thread for hours. - Cancellation. Closing the window cancels the token,
SCardCancelends the wait, the loop exits, andusingreleases the context. A connect and transmit take milliseconds and are not interrupted.Stop()waits up to 3 seconds and then lets the window close anyway. - Reader removal. When the reader is unplugged, its state entry reports
UNKNOWNorUNAVAILABLE(or the wait returnsSCARD_E_UNKNOWN_READER). The worker reports "Reader removed" and goes back to looking for a reader. While none is connected, it waits on the PnP notification entry. The wait has a 5-second time-out, so a missed notification costs at most 5 seconds. - Service stop. Windows may stop the Smart Card service when no reader is connected.
SCARD_E_NO_SERVICE,SCARD_E_SERVICE_STOPPEDandSCARD_E_INVALID_HANDLEmean the context is dead. The worker shows "No reader (Smart Card service not running)" and creates a new context every 2 seconds, as in the detection guide.
Project Setup (.NET 10 Windows Forms)
- Install the ACS driver and check the reader with the driver guide and the PC/SC status check. The app cannot see a reader that PC/SC does not list.
- Create the project:
dotnet new winforms -n NfcReaderApp. With the .NET 10 SDK the template already targetsnet10.0-windows. Delete the template'sForm1.csandForm1.Designer.cs. - Copy the two shared files
WinScard.csandPcsc.csfrom the C# tutorial into aPcscfolder, unchanged. Every.csfile under the project folder is compiled. - Add the five files below, replacing the template's
Program.cs. Then rundotnet build. Expected result: "Build succeeded", 0 warnings, 0 errors.
NfcReaderApp\
NfcReaderApp.csproj
Program.cs entry point
MainForm.cs the window (UI thread)
ReaderWorker.cs the reader thread
ScanRecord.cs log row, messages to the UI, CSV export
CardType.cs card type from the ATR
Pcsc\WinScard.cs from the C# tutorial, unchanged
Pcsc\Pcsc.cs from the C# tutorial, unchanged
The project file. No NuGet packages are needed:
Compiled by BSD; not yet tested on a reader. All code on this page was built on 1 Dec 2026 for net10.0-windows with the .NET 10 SDK: 0 warnings, 0 errors, warnings treated as errors. BSD started the app on a Windows 11 PC with no ACS reader. It showed "No reader. Plug in an ACS contactless reader." and closed cleanly in under a second. Tests with ACS readers and cards are still to be done.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<UseWindowsForms>true</UseWindowsForms>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode>
<AssemblyTitle>BSD NFC Reader App (sample)</AssemblyTitle>
</PropertyGroup>
<!-- Pcsc\WinScard.cs and Pcsc\Pcsc.cs are unchanged copies of the Day 35 shared files. -->
</Project>
// Program.cs: entry point of the BSD NFC Reader App sample. C# 14, .NET 10, Windows Forms.
// Compiled by BSD; not yet tested on a reader.
namespace Bsd.NfcReaderApp;
internal static class Program
{
[STAThread]
private static void Main()
{
ApplicationConfiguration.Initialize(); // high-DPI mode and visual styles from the project file
Application.Run(new MainForm());
}
}
.NET version: The project targets .NET 10, the current long-term support release. Microsoft's .NET support policy lists .NET 10 as supported until 14 November 2028; .NET 8 support ended on 10 November 2026.
The Reader Thread: ReaderWorker.cs
This is the important file. It has three nested loops. Run keeps a PC/SC context alive and makes a new one if the service stops. RunSession finds a reader or waits for one. WatchReader reads each arriving card until the reader is removed. The card logic is the same as the UID read loop: act only when PRESENT appears, connect in shared mode, send Get Data, and disconnect with SCARD_LEAVE_CARD. Here the result goes into a ScanRecord instead of the console.
Compiled by BSD; not yet tested on a reader. Read-only: Get Data FF CA 00 00 00 only, and only to a PICC reader entry.
// ReaderWorker.cs: the reader thread. It owns its own PC/SC context, waits for readers and cards,
// reads each card once (ATR + UID) and reports to the UI through IProgress. C# 14, .NET 10, Windows.
// Read-only: the only card command is Get Data FF CA 00 00 00. No keys, no reads of card memory, no writes.
// Compiled by BSD; not yet tested on a reader.
using Bsd.Pcsc;
namespace Bsd.NfcReaderApp;
public sealed class ReaderWorker
{
private readonly IProgress<ReaderUpdate> _progress;
private CancellationTokenSource? _cts;
private Task? _task;
/// <param name="progress">Create it on the UI thread (new Progress<T>(handler)) so the handler runs there.</param>
public ReaderWorker(IProgress<ReaderUpdate> progress) => _progress = progress;
public void Start()
{
if (_task is not null) return;
_cts = new CancellationTokenSource();
// LongRunning: a dedicated thread, because SCardGetStatusChange blocks for as long as nothing happens.
_task = Task.Factory.StartNew(() => Run(_cts.Token), CancellationToken.None,
TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
/// <summary>Cancels the wait (SCardCancel) and waits for the thread to finish, at most timeoutMs.</summary>
public bool Stop(int timeoutMs = 3000)
{
if (_task is null || _cts is null) return true;
_cts.Cancel();
bool finished = _task.Wait(timeoutMs); // Run() catches its own exceptions, so Wait does not throw
_cts.Dispose();
_task = null;
_cts = null;
return finished;
}
private void Report(ReaderStatus status, string message, string? reader = null, ScanRecord? scan = null) =>
_progress.Report(new ReaderUpdate(status, message, reader, scan));
// Outer loop: one PC/SC context per pass. A new context is made after the Smart Card service stops.
private void Run(CancellationToken token)
{
Report(ReaderStatus.Starting, "Starting...");
while (!token.IsCancellationRequested)
{
try
{
using var pcsc = new PcscContext();
RunSession(pcsc, token);
}
catch (OperationCanceledException)
{
return;
}
catch (PcscException ex) when (PcscErrors.ContextLost(ex.Code))
{
// Windows 8 and later may stop the Smart Card service when no reader is connected,
// so "no service" usually just means "no reader yet". Try again every 2 seconds.
Report(ReaderStatus.NoService, "No reader (Smart Card service not running). Plug in an ACS reader.");
if (token.WaitHandle.WaitOne(2000)) return;
}
catch (Exception ex)
{
Report(ReaderStatus.Error, ex.Message + " Retrying in 5 s.");
if (token.WaitHandle.WaitOne(5000)) return;
}
}
}
// Inner loop: find a contactless reader, watch it until it is removed, then look again.
private void RunSession(PcscContext pcsc, CancellationToken token)
{
while (true)
{
string? reader = PickReader(pcsc.ListReaders());
if (reader is null)
{
Report(ReaderStatus.NoReader, "No reader. Plug in an ACS contactless reader.");
WaitForReaderArrival(pcsc, token);
continue;
}
Report(ReaderStatus.Ready, "Ready. Tap a card.", reader);
WatchReader(pcsc, reader, token);
Report(ReaderStatus.NoReader, "Reader removed: " + reader);
}
}
// First ACS contactless (PICC) entry, else any PICC entry. SAM and contact (ICC) entries are skipped.
private static string? PickReader(string[] readers) =>
readers.FirstOrDefault(r => r.StartsWith("ACS ", StringComparison.OrdinalIgnoreCase)
&& r.Contains("PICC", StringComparison.OrdinalIgnoreCase))
?? readers.FirstOrDefault(r => r.Contains("PICC", StringComparison.OrdinalIgnoreCase));
// Waits on the PnP entry, which changes when a reader is added or removed. The 5 s time-out is a safety net:
// the caller lists the readers again either way, so a missed notification costs at most 5 seconds.
private static void WaitForReaderArrival(PcscContext pcsc, CancellationToken token)
{
var pnp = new[] { PcscContext.NewState(WinScard.PnpNotification) };
try
{
pcsc.WaitForChange(pnp, 0, token); // learn the current value
PcscContext.Acknowledge(pnp);
pcsc.WaitForChange(pnp, 5000, token);
}
catch (PcscException ex) when (ex.Code == WinScard.SCARD_E_NO_READERS_AVAILABLE)
{
if (token.WaitHandle.WaitOne(2000)) throw new OperationCanceledException(token);
}
}
// Returns when the reader is removed. Each card is handled once, when it arrives.
private void WatchReader(PcscContext pcsc, string reader, CancellationToken token)
{
var state = new[] { PcscContext.NewState(reader) };
try
{
pcsc.WaitForChange(state, 0, token); // current state at once: a card already on the reader is read
while (true)
{
uint now = state[0].dwEventState, was = state[0].dwCurrentState;
if ((now & (WinScard.SCARD_STATE_UNKNOWN | WinScard.SCARD_STATE_UNAVAILABLE)) != 0) return;
// A card arrived: PRESENT is new, or the insertion counter in the upper 16 bits moved (quick swap).
bool arrived = (now & WinScard.SCARD_STATE_PRESENT) != 0
&& ((was & WinScard.SCARD_STATE_PRESENT) == 0 || (was & 0xFFFF0000) != (now & 0xFFFF0000));
if (arrived)
{
Report(ReaderStatus.CardPresent, "Card on the reader. Remove it and tap the next card.", reader,
ReadCard(pcsc, reader, state[0]));
}
else if ((now & WinScard.SCARD_STATE_EMPTY) != 0 && (was & WinScard.SCARD_STATE_PRESENT) != 0)
{
Report(ReaderStatus.Ready, "Ready. Tap a card.", reader);
}
PcscContext.Acknowledge(state);
pcsc.WaitForChange(state, WinScard.INFINITE, token);
}
}
catch (PcscException ex) when (ex.Code is WinScard.SCARD_E_UNKNOWN_READER or WinScard.SCARD_E_READER_UNAVAILABLE)
{
// The reader was unplugged during the wait: same as UNKNOWN/UNAVAILABLE above.
}
}
// ATR from the reader state (no connection needed), then connect, send FF CA 00 00 00, disconnect.
private static ScanRecord ReadCard(PcscContext pcsc, string reader, WinScard.SCARD_READERSTATE s)
{
byte[] atr = PcscContext.Atr(s);
string atrHex = Apdu.HexSpaced(atr), type = CardType.FromAtr(atr);
ScanRecord Row(string uid, string result) => new(DateTime.Now, reader, uid, type, atrHex, result);
if ((s.dwEventState & WinScard.SCARD_STATE_MUTE) != 0) return Row("", "Card does not answer (MUTE)");
try
{
using CardConnection card = pcsc.Connect(reader); // shared mode; disconnects with LEAVE_CARD
byte[] reply = card.Transmit(Apdu.GetUid);
return Apdu.IsSuccess(reply)
? Row(Apdu.Hex(Apdu.Data(reply)), "OK")
: Row("", "Get Data refused, status " + Apdu.StatusWord(reply));
}
catch (PcscException ex) when (ex.Code is WinScard.SCARD_W_REMOVED_CARD or WinScard.SCARD_E_NO_SMARTCARD)
{
return Row("", "Card removed too early; tap again");
}
catch (PcscException ex) when (ex.Code == WinScard.SCARD_E_SHARING_VIOLATION)
{
return Row("", "Another program is using the card");
}
catch (PcscException ex) when (!PcscErrors.ContextLost(ex.Code))
{
return Row("", ex.Message);
}
}
}
Points to keep if you change it:
- Every
catchinReadCardturns a failed read into a log row. A card pulled away too early, or held by another program, must not stop the reader thread. - Errors that mean the context is dead are not caught in
ReadCard. They pass up toRun, which makes a new context. Runcatches every exception and retries. An exception that escaped would end the thread silently, and the window would keep saying "Ready" while nothing is read.- The upper 16 bits of the event state are compared, not decoded. Windows does not document them; pcsc-lite documents them as an insertion and removal counter. Comparing them only adds a read when a quick card swap would otherwise be missed.
The Window: MainForm.cs
The form is built in code: a status bar, the reader name, the last card (UID, card type, ATR, in read-only text boxes so they can be copied), the log as a ListView, and two buttons. The parts that matter for an NFC app are the Progress<ReaderUpdate> created in the constructor, Shown starting the worker, FormClosing stopping it, and the IsDisposed check in OnReaderUpdate. That check covers an update posted just before the window closed.
Compiled by BSD; not yet tested on a reader.
// MainForm.cs: the window. Built in code (no designer file) so the whole UI fits on one page.
// Everything here runs on the UI thread; the reader thread only talks to it through Progress<T>.
// C# 14, .NET 10, Windows Forms. Compiled by BSD; not yet tested on a reader.
namespace Bsd.NfcReaderApp;
public sealed class MainForm : Form
{
private readonly Label _status = new() { Dock = DockStyle.Top, Height = 40, Padding = new Padding(10, 0, 0, 0),
TextAlign = ContentAlignment.MiddleLeft, Font = new Font("Segoe UI", 12f, FontStyle.Bold) };
private readonly Label _reader = new() { Dock = DockStyle.Top, Height = 24, Padding = new Padding(10, 0, 0, 0),
TextAlign = ContentAlignment.MiddleLeft, Text = "Reader: -" };
private readonly TextBox _uid = ReadOnlyBox(new Font("Consolas", 20f, FontStyle.Bold));
private readonly TextBox _type = ReadOnlyBox(new Font("Segoe UI", 10f));
private readonly TextBox _atr = ReadOnlyBox(new Font("Consolas", 10f));
private readonly ListView _log = new() { Dock = DockStyle.Fill, View = View.Details, FullRowSelect = true, GridLines = true };
private readonly Label _count = new() { AutoSize = true, Padding = new Padding(0, 8, 0, 0), Text = "0 scans" };
private readonly List<ScanRecord> _scans = [];
private readonly ReaderWorker _worker;
public MainForm()
{
Text = "BSD NFC Reader App (sample)";
ClientSize = new Size(900, 560);
MinimumSize = new Size(640, 420);
StartPosition = FormStartPosition.CenterScreen;
// Progress<T> captures the UI thread's SynchronizationContext here, in the constructor.
// Every Report() from the reader thread is then posted (not sent) to OnReaderUpdate on the UI thread.
_worker = new ReaderWorker(new Progress<ReaderUpdate>(OnReaderUpdate));
var card = new TableLayoutPanel { Dock = DockStyle.Top, Height = 120, ColumnCount = 2, Padding = new Padding(10, 4, 10, 4) };
card.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 90));
card.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100));
AddRow(card, "UID", _uid);
AddRow(card, "Card type", _type);
AddRow(card, "ATR", _atr);
foreach (var (name, width) in new[] { ("Time", 140), ("UID", 170), ("Card type", 180), ("Result", 170), ("Reader", 220), ("ATR", 360) })
_log.Columns.Add(name, width);
var export = new Button { Text = "Export CSV...", AutoSize = true };
var clear = new Button { Text = "Clear log", AutoSize = true };
export.Click += (_, _) => ExportCsv();
clear.Click += (_, _) => { _scans.Clear(); _log.Items.Clear(); _count.Text = "0 scans"; };
var buttons = new FlowLayoutPanel { Dock = DockStyle.Bottom, Height = 40, Padding = new Padding(6) };
buttons.Controls.AddRange([export, clear, _count]);
// Dock order: the last control added to Controls is docked first.
Controls.Add(_log);
Controls.Add(buttons);
Controls.Add(card);
Controls.Add(_reader);
Controls.Add(_status);
SetStatus(ReaderStatus.Starting, "Starting...");
Shown += (_, _) => _worker.Start();
FormClosing += (_, _) => _worker.Stop(); // SCardCancel ends the wait; the thread exits within milliseconds
}
// Runs on the UI thread (see the Progress<T> note above), so controls can be changed directly.
private void OnReaderUpdate(ReaderUpdate u)
{
if (IsDisposed) return; // an update posted just before the window closed
SetStatus(u.Status, u.Message);
if (u.Reader is not null) _reader.Text = "Reader: " + u.Reader;
else if (u.Status is ReaderStatus.NoReader or ReaderStatus.NoService) _reader.Text = "Reader: -";
if (u.Scan is { } s) AddScan(s);
}
private void SetStatus(ReaderStatus status, string message)
{
_status.Text = message;
_status.BackColor = status switch
{
ReaderStatus.Ready => Color.FromArgb(220, 245, 225),
ReaderStatus.CardPresent => Color.FromArgb(210, 230, 250),
ReaderStatus.Error => Color.FromArgb(250, 220, 220),
_ => Color.FromArgb(250, 240, 210) // starting, no service, no reader
};
}
private void AddScan(ScanRecord s)
{
_scans.Add(s);
_uid.Text = s.Uid.Length > 0 ? s.Uid : "(not read)";
_type.Text = s.CardType;
_atr.Text = s.Atr;
var item = new ListViewItem([s.Time.ToString("yyyy-MM-dd HH:mm:ss"), s.Uid, s.CardType, s.Result, s.Reader, s.Atr]);
_log.Items.Insert(0, item); // newest first
_count.Text = _scans.Count == 1 ? "1 scan" : $"{_scans.Count} scans";
}
private void ExportCsv()
{
if (_scans.Count == 0)
{
MessageBox.Show(this, "The log is empty.", Text);
return;
}
using var dialog = new SaveFileDialog
{
Filter = "CSV file (*.csv)|*.csv",
FileName = $"scans-{DateTime.Now:yyyyMMdd-HHmmss}.csv"
};
if (dialog.ShowDialog(this) != DialogResult.OK) return;
try
{
CsvExport.Write(dialog.FileName, _scans);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
MessageBox.Show(this, "Could not save the file: " + ex.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private static TextBox ReadOnlyBox(Font font) =>
new() { ReadOnly = true, BorderStyle = BorderStyle.None, Dock = DockStyle.Fill, Font = font, BackColor = SystemColors.Window };
private static void AddRow(TableLayoutPanel panel, string caption, Control value)
{
panel.RowStyles.Add(new RowStyle(SizeType.AutoSize));
panel.Controls.Add(new Label { Text = caption, AutoSize = true, Padding = new Padding(0, 6, 0, 0) });
panel.Controls.Add(value);
}
}
The card type column comes from the ATR. The decoder is a shortened version of the one in the ATR decoding section, which explains the byte layout and where each value comes from:
Compiled by BSD; not yet tested on a reader. The card names are from ACS reference manuals, not from BSD's own readers. Which name an NTAG reports is one of the hardware checks.
// CardType.cs: a short card-type name from the ATR a contactless reader builds (PC/SC Part 3).
// C# 14, .NET 10. Same rules as the Day 37 ATR decoder, shortened for a grid column.
// Card-name values: ACS ACR1552U reference manual v1.05 (5.3.1.1) and ACR122U API manual v1.4 (3.1.1).
// Compiled by BSD; not yet tested on a reader.
namespace Bsd.NfcReaderApp;
public static class CardType
{
public static string FromAtr(byte[] atr)
{
// Built ATR: 3B 8n 80 01, n historical bytes, TCK.
if (atr.Length < 5 || atr[0] != 0x3B || (atr[1] & 0xF0) != 0x80 || atr[2] != 0x80 || atr[3] != 0x01)
return "Unknown (not a PC/SC contactless ATR)";
int n = atr[1] & 0x0F;
if (atr.Length < 5 + n) return "Unknown (ATR too short)";
byte[] hist = atr[4..(4 + n)];
// Storage cards: 80 4F 0C A0 00 00 03 06 SS C0 C1 00 00 00 00.
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 "ISO 14443-4 card (e.g. DESFire)";
int name = hist[9] << 8 | hist[10];
return name switch
{
0x0001 => "MIFARE Classic 1K",
0x0002 => "MIFARE Classic 4K",
0x0003 => "MIFARE Ultralight family",
0x0026 => "MIFARE Mini",
0x003A => "MIFARE Ultralight C",
0x0036 or 0x0037 or 0x0038 or 0x0039 => "MIFARE Plus (SL1/SL2)",
0x0030 or 0xF004 => "Topaz / Jewel",
0x003B or 0xF011 or 0xF012 => "FeliCa",
_ => $"Storage card, name {name:X4}"
};
}
}
Scan Log and CSV Export
ScanRecord is one log row. ReaderUpdate is the only type the reader thread sends to the window. CsvExport writes the log in RFC 4180 style: fields that contain a comma, quote or line break are quoted. Times are written as yyyy-MM-dd HH:mm:ss (local time), so they sort correctly as text. The file is UTF-8 with a byte-order mark so that Excel opens it as UTF-8.
Compiled by BSD; not yet tested on a reader.
// ScanRecord.cs: one row of the scan log, the worker's messages to the UI, and CSV export.
// C# 14, .NET 10, Windows. Compiled by BSD; not yet tested on a reader.
using System.Globalization;
using System.Text;
namespace Bsd.NfcReaderApp;
/// <summary>One card tap. Uid is empty when the card could not be read; Result then says why.</summary>
public sealed record ScanRecord(DateTime Time, string Reader, string Uid, string CardType, string Atr, string Result);
public enum ReaderStatus { Starting, NoService, NoReader, Ready, CardPresent, Error }
/// <summary>What the reader thread reports to the UI thread. Scan is set only when a card was handled.</summary>
public sealed record ReaderUpdate(ReaderStatus Status, string Message, string? Reader = null, ScanRecord? Scan = null);
public static class CsvExport
{
/// <summary>Writes the log as CSV: UTF-8 with BOM (Excel then reads it as UTF-8), ISO-style local time.</summary>
public static void Write(string path, IEnumerable<ScanRecord> rows)
{
var sb = new StringBuilder();
sb.AppendLine("Time,UID,Card type,Reader,ATR,Result");
foreach (var r in rows)
{
sb.Append(r.Time.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture)).Append(',')
.Append(Field(r.Uid)).Append(',')
.Append(Field(r.CardType)).Append(',')
.Append(Field(r.Reader)).Append(',')
.Append(Field(r.Atr)).Append(',')
.Append(Field(r.Result)).AppendLine();
}
File.WriteAllText(path, sb.ToString(), new UTF8Encoding(encoderShouldEmitUTF8Identifier: true));
}
// RFC 4180: quote a field that holds a comma, quote or line break, and double any quote inside it.
private static string Field(string value) =>
value.IndexOfAny([',', '"', '\r', '\n']) >= 0 ? "\"" + value.Replace("\"", "\"\"") + "\"" : value;
}
Excel and hex UIDs: double-clicking a CSV lets Excel guess each column's type. A UID made only of digits loses its leading zeros. A UID such as 1234E567 is read as a number in scientific notation. To keep UIDs exactly, import with Data > From Text/CSV and set the UID column to Text. Other programs should read the file as CSV text. If the UIDs must match another system's format (reversed bytes or decimal), see UID byte order.
The log lives in memory and is lost when the app closes, unless you export it. For attendance or access use, write each ScanRecord to a database or file on the UI thread in AddScan, or on a separate writer thread. Never do it on the reader thread, or a slow disk or network will delay the next tap.
Build, Run and What to Expect
dotnet buildin the project folder. Expected result: "Build succeeded", 0 warnings, 0 errors.dotnet run. Expected result: the window opens and shows "Starting...", then either "No reader..." (yellow) or "Ready. Tap a card." (green) with the reader name. On a PC without an ACS reader, BSD saw "No reader. Plug in an ACS contactless reader." Virtual smart cards and contact readers are not PICC entries, so they are ignored.- Plug in the reader while the app runs. Expected result: within a few seconds, "Ready. Tap a card." and the reader name.
- Tap a card. Expected result: the status turns blue ("Card on the reader"), and the UID, card type and ATR appear with a new log row marked "OK". A MIFARE Classic 1K should show a 4-byte UID (8 hex digits) or a 7-byte one, and "MIFARE Classic 1K". A DESFire card should show "ISO 14443-4 card (e.g. DESFire)". These are expectations from the ACS manuals, not yet BSD results.
- Remove the card and the status returns to "Ready". Leaving a card on the reader adds no further rows.
- Unplug the reader. Expected result: "Reader removed: ...". Plug it back in and reading starts again.
- Export CSV... saves the log; close the window and the app ends within a second.
Packaging and Deployment
Two things must be on every PC that runs the app: the ACS reader driver and either the .NET Desktop Runtime or a self-contained build of the app. winscard.dll and the Smart Card service are part of Windows, so nothing PC/SC-related needs to be installed.
| Option | Command | The target PC needs |
|---|---|---|
| Self-contained, single file (recommended for shop-floor and kiosk PCs) | dotnet publish -c Release -r win-x64 --self-contained true -p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true | The ACS driver only. Copy the one .exe. |
| Framework-dependent | dotnet publish -c Release | The ACS driver and the .NET Desktop Runtime of the same major version (10) |
| 32-bit Windows | As above with -r win-x86 | As above |
- Size: a self-contained file includes the .NET runtime and Windows Forms, so it is much larger than the framework-dependent build. Adding
-p:EnableCompressionInSingleFile=truemakes it smaller but slower to start. BSD has not yet measured the sizes for this app. - Do not trim. Windows Forms does not support trimming, so leave
PublishTrimmedoff. Native AOT does not support Windows Forms either. - Self-extraction: with
IncludeNativeLibrariesForSelfExtract, Windows extracts the native runtime files to a folder under%TEMP%\.netthe first time the app runs. Some locked-down PCs block that. If so, publish without single file and copy the whole publish folder. - Driver first: install the driver from the official ACS page for the model: ACR1252U, ACR1552U, ACR122U. The steps and the common errors are in the Windows driver guide. Install the driver before the first plug-in, and check the reader once with the PC/SC status check on each new PC.
- Remote Desktop: in an RDP session, programs see the readers of the client PC (if smart card redirection is on), not the server's. See readers over Remote Desktop.
- Signing: an unsigned
.execopied from a network share may trigger a SmartScreen warning. Sign it with your organisation's code-signing certificate before wide roll-out.
The framework-dependent publish was run by BSD on 1 Dec 2026 and completed without errors. The self-contained publish was not run, because it needs runtime packs that BSD's build PC did not have stored locally.
Next Steps: From Sample to Real Application
The sample proves the plumbing. A production attendance, access or canteen application usually adds the following, most of it on the UI side or in a service behind it, with the reader thread left as it is:
- Look-up: match the UID to a person, card or account in your database, and show a name or "unknown card" instead of hex.
- Feedback at the reader: a beep or LED colour for "accepted" and "refused", sent as a reader control command after the read. See ACS reader LED and buzzer control.
- Duplicate rules: for example, ignore the same UID twice within 30 seconds at a canteen counter.
- Storage and sync: write each scan to a local database straight away, and send it to the central system when the network is up.
- Card data, not only the UID: when a UID is not secure enough, read authenticated data from the card. Start with APDU commands and reading MIFARE Classic cards in C#, and plan your card keys carefully.
- Settings: a reader-name filter for PCs with more than one reader, and a log folder.
Need it built rather than built yourself?
BSD Infotech supplies ACS readers and cards and develops the software around them. That includes attendance and access applications, canteen and cashless systems, enrolment tools and integration with your existing database or ERP. See NFC and smart card application development, or tell us about your application.
Troubleshooting the .NET NFC Application
| What you see | Likely cause | What to do |
|---|---|---|
| "No reader" with the reader plugged in | Driver not installed, or the reader has no PICC entry in its PC/SC name | Check the reader with the PC/SC status check; see the reader names per model. |
| "Smart Card service not running" never clears | Service disabled, or the reader is not detected by Windows | See the Smart Card service and reader detection in Windows. |
| The window freezes | PC/SC called on the UI thread, or Control.Invoke used during shutdown | Keep every PC/SC call in ReaderWorker; report with Progress<T> (it posts). |
InvalidOperationException: cross-thread operation | A control changed from the reader thread | Create the Progress<T> on the UI thread (in the form's constructor), not inside the worker. |
| "Card removed too early; tap again" | Card tapped and pulled away quickly | Hold the card flat on the reader for a moment. This happens occasionally; the app carries on. |
| "Another program is using the card" | QuickView, Script Tool or a second copy of the app is connected | Close the other program. Run one copy of the app per reader. |
| "Get Data refused, status 6A 81" | Get Data not supported for this card or reader mode | Check the card type; see UID troubleshooting in C#. |
| Different UID on every tap | Random ID turned on in the card (some DESFire cards) | Use another identifier; see UID troubleshooting. |
| App does not start on another PC | Framework-dependent build without the .NET Desktop Runtime | Publish self-contained, or install the matching Desktop Runtime. |
| UIDs changed in Excel | Excel converted the UID column to numbers | Import with Data > From Text/CSV and set the UID column to Text. |
Sources
Checked on 30 Nov 2026 (support policy rechecked on 1 Dec 2026): Microsoft's .NET support policy (.NET 10 is the current long-term support release, supported until 14 November 2028; .NET 8 support ended 10 November 2026), Microsoft's single-file deployment documentation, and the Win32 reference for the PC/SC calls. The card-type values are from the ACS ACR1552U Series reference manual v1.05 and ACR122U API manual v1.4, read for the UID guide.
- Microsoft: .NET and .NET Core support policy
- Microsoft: single-file deployment
- Microsoft: SCardGetStatusChange, SCardCancel
- Official ACS drivers and manuals: ACR1252U, ACR1552U, ACR122U (acs.com.hk)
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 and NTAG are trademarks of NXP B.V. Windows, .NET and Excel are trademarks of Microsoft Corporation.
