Reading CBOR Data Incrementally in .NET
C# Corner walks through reading CBOR data with the System.Formats.Cbor package, from a basic CborReader example to buffering partial network reads. It stresses separating incomplete input from malformed data, enforcing size limits and defining message boundaries. Useful for services that receive binary payloads from devices or APIs.
Key points
- Check which reader APIs your target framework and System.Formats.Cbor version support before relying on incremental features.
- Use CborReader to decode values in the order they were written, and check BytesRemaining for trailing data.
- A single stream read can return a partial CBOR value, so keep unconsumed bytes buffered between reads.
- Enforce a maximum payload size while reading, not only after the whole message is loaded.
- Retry incomplete input only until more bytes arrive; reject malformed data outright.
- CBOR does not define message boundaries, so separate messages with a length prefix or protocol framing.
CBOR (Concise Binary Object Representation) is a compact binary format for structured data, often used for device telemetry and binary protocols. This tutorial shows how .NET applications decode it with CborReader from the System.Formats.Cbor package, reading a small array of device ID, temperature and status flag. It notes that the available APIs depend on the package version and target framework.
The core challenge is fragmented input: one network read may return only part of a message, so the application must keep unconsumed bytes between reads. The article shows a buffering helper with a size limit, then points to System.IO.Pipelines and sequence-aware parsing for truly incremental work. It also separates incomplete input, which may become valid later, from malformed input, which should be rejected rather than retried.
Real-world use
- An IoT ingestion service receiving compact telemetry from thousands of devices over HTTP or TCP.
- A gateway that parses binary messages from a partner API and validates their structure before processing.
- A background worker reading large CBOR files or queued payloads without loading them fully into memory.
Why it matters
If your service accepts binary payloads, you need size limits, fragment-aware buffering and strict validation from the start. The article is a sound checklist, though the exact implementation depends on your package version.
Related stories
- Collection Return Types in C#: Interfaces, Views, and SnapshotsNick Cosentino (Dev Leader)2 d ago
- Dynamic Gauss-Legendre numerical integration in C#: computing nodes and weights on the fly without overflowHabr C# (ru)2 d ago
- Events and Delegates in C#: Contracts, Subscriptions and NotificationNick Cosentino (Dev Leader)3 d ago