Sphere10.Framework.Windows.LevelDB 3.2.0

dotnet add package Sphere10.Framework.Windows.LevelDB --version 3.2.0
                    
NuGet\Install-Package Sphere10.Framework.Windows.LevelDB -Version 3.2.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Sphere10.Framework.Windows.LevelDB" Version="3.2.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Sphere10.Framework.Windows.LevelDB" Version="3.2.0" />
                    
Directory.Packages.props
<PackageReference Include="Sphere10.Framework.Windows.LevelDB" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Sphere10.Framework.Windows.LevelDB --version 3.2.0
                    
#r "nuget: Sphere10.Framework.Windows.LevelDB, 3.2.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Sphere10.Framework.Windows.LevelDB@3.2.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Sphere10.Framework.Windows.LevelDB&version=3.2.0
                    
Install as a Cake Addin
#tool nuget:?package=Sphere10.Framework.Windows.LevelDB&version=3.2.0
                    
Install as a Cake Tool

💾 Sphere10.Framework.Windows.LevelDB

Sphere10.Framework.Windows.LevelDB is a .NET wrapper for Google's LevelDB, an embedded key-value store that keeps its keys in sorted order. Use it on Windows when an application needs a local, persistent map from string or byte-array keys to values, with atomic batches, ordered iteration and consistent snapshots.

📦 Installation

dotnet add package Sphere10.Framework.Windows.LevelDB

The package targets net8.0, net9.0 and net10.0, and also net11.0 when it is built with a .NET 11 SDK. It belongs to the Windows solution, src/Sphere10.Framework (Win).sln, whose projects reference src/Sphere10.Framework.Windows.LevelDB/Sphere10.Framework.Windows.LevelDB.csproj directly.

📋 Overview

The package embeds 32-bit and 64-bit builds of the native LevelDB.dll. On first use, LevelDBInterop writes the build that matches the process to %APPDATA%\Sphere10.Framework\Sphere10.Framework.Windows.LevelDB-<assembly version>\x32 or \x64, and then loads it with the Windows LoadLibrary function. A file that already exists at that path is reused.

All types are in the Sphere10.Framework.Windows.LevelDB namespace.

Type Role
DB Opens a database directory, reads and writes entries, and creates iterators and snapshots
Options, ReadOptions, WriteOptions Settings for opening a database, for reads and for writes
WriteBatch Updates that DB.Write applies atomically, in the order they were added
Iterator Moves through the entries in key order
SnapShot A fixed view of the database for consistent reads
Cache, Comparator, Env An LRU block cache, a custom key order and the default operating-system environment
LevelDBException The error that LevelDB reports

🔧 Usage

Basic CRUD Operations

using Sphere10.Framework.Windows.LevelDB;

using var db = new DB(@"C:\Data\cities", new Options { CreateIfMissing = true });

db.Put("Tampa", "green");
db.Put("London", "red");

string color = db.Get("Tampa");   // "green"
db.Delete("London");              // deleting a missing key is not an error
bool removed = db.Get("London") == null;

String keys and values are stored as UTF-8. Put, Get and Delete also take byte[] keys and values, and an optional WriteOptions or ReadOptions.

Batch Writes

using (var batch = new WriteBatch()) {
	batch.Delete("London")
		.Put("Paris", "blue")
		.Put("Tokyo", "white");
	db.Write(batch);
}

Byte-Array Keys and Durable Writes

using System.Buffers.Binary;
using System.Text;
using Sphere10.Framework.Windows.LevelDB;

using var blocks = new DB(@"C:\Data\blocks", new Options { CreateIfMissing = true });

var key = new byte[8];
BinaryPrimitives.WriteInt64BigEndian(key, 42);   // big-endian numbers sort in numeric order
byte[] payload = Encoding.UTF8.GetBytes("block 42");

using (var durable = new WriteOptions { Sync = true }) {
	blocks.Put(key, payload, durable);
}

byte[] stored = blocks.Get(key);   // null when the key is missing

using (var iterator = blocks.CreateIterator()) {
	for (iterator.SeekToLast(); iterator.IsValid(); iterator.Prev()) {
		long height = BinaryPrimitives.ReadInt64BigEndian(iterator.GetKey());
		byte[] value = iterator.GetValue();
	}
}

The default comparator orders keys byte by byte, so write non-negative numeric keys big-endian to keep them in numeric order. Keep keys of one layout in their own database, so that a decoder such as ReadInt64BigEndian never meets a key of another shape. SeekToLast and Prev walk the entries from the highest key down. Pass a WriteOptions with Sync set to DB.Write as well, when a whole batch must reach the disk before the call returns.

Iterating Over Data

using System;
using System.Collections.Generic;
using System.Linq;

using (var iterator = db.CreateIterator()) {
	for (iterator.Seek("P"); iterator.IsValid(); iterator.Next())
		Console.WriteLine($"{iterator.GetStringKey()}: {iterator.GetStringValue()}");
}

// DB also enumerates every entry in key order, from a snapshot taken when the enumeration starts.
var keys = (db as IEnumerable<KeyValuePair<string, string>>).Select(entry => entry.Key).ToList();

A new iterator is invalid until Seek, SeekToFirst or SeekToLast positions it. Seek moves to the first key at or after its argument, and Next and Prev step from there. DB implements both IEnumerable<KeyValuePair<string, string>> and IEnumerable<KeyValuePair<byte[], byte[]>>, so cast it to choose the string view for LINQ.

Point-in-Time Snapshots

db.Put("Tampa", "green");

using (var snapshot = db.CreateSnapshot()) {
	var asOfSnapshot = new ReadOptions { Snapshot = snapshot };
	db.Put("Tampa", "yellow");

	string then = db.Get("Tampa", asOfSnapshot);   // "green"
	string now = db.Get("Tampa");                  // "yellow"
}

A snapshot is immutable, so several threads can read through it without locking. Pass it in ReadOptions.Snapshot to Get or to CreateIterator.

New keys and deletes follow the same rule, and an iterator created with the snapshot's read options walks the contents as they were.

db.Put("Tampa", "green");
db.Put("London", "red");

using (var snapshot = db.CreateSnapshot())
using (var asOfSnapshot = new ReadOptions { Snapshot = snapshot }) {
	db.Put("New York", "blue");
	db.Delete("London");

	string added = db.Get("New York", asOfSnapshot);   // null, because the key was added after the snapshot
	string deleted = db.Get("London", asOfSnapshot);   // "red", because the snapshot still holds it

	using var iterator = db.CreateIterator(asOfSnapshot);
	for (iterator.SeekToFirst(); iterator.IsValid(); iterator.Next())
		Console.WriteLine(iterator.GetStringKey());     // includes London, excludes New York
}

string current = db.Get("London");   // null, because the database itself has the delete

Options

Setting Effect
Options.CreateIfMissing Creates the database when the directory has none
Options.ErrorIfExists Fails when the database already exists
Options.ParanoidChecks Checks stored data aggressively and stops at the first error
Options.WriteBufferSize Memory to fill before writing a sorted file (default 4 MB)
Options.MaxOpenFiles The open-file budget (default 1000)
Options.BlockSize Uncompressed data per block (default 4 KB)
Options.RestartInterval Keys between delta-encoding restart points (default 16)
Options.CompressionLevel NoCompression, or SnappyCompression, which is LevelDB's default
Options.Cache A Cache(capacity) LRU block cache, instead of LevelDB's internal 8 MB cache
Options.Comparator A Comparator that replaces the default key order
Options.Env The Env that performs file and background operations
ReadOptions.VerifyCheckSums, FillCache, Snapshot Verifies checksums, skips caching for bulk scans, or reads from a snapshot
WriteOptions.Sync Flushes each write to disk before it completes, which is slower but keeps recent writes through a machine crash

These properties have setters only, except Env, Cache and Comparator. Do not change an Options object after a DB has opened with it.

using Sphere10.Framework.Windows.LevelDB;

using var cache = new Cache(64 * 1024 * 1024);   // 64 MB LRU block cache
using var options = new Options {
	CreateIfMissing = true,
	Cache = cache,
	WriteBufferSize = 16 * 1024 * 1024,
	MaxOpenFiles = 500,
	CompressionLevel = CompressionLevel.SnappyCompression
};
using var ledger = new DB(@"C:\Data\ledger", options);

// A one-off scan over every entry should not push hot blocks out of the cache.
using var bulkScan = new ReadOptions { FillCache = false, VerifyCheckSums = true };
using var iterator = ledger.CreateIterator(bulkScan);
for (iterator.SeekToFirst(); iterator.IsValid(); iterator.Next()) {
	byte[] value = iterator.GetValue();
}

using var disposes in reverse order, so the iterator closes before the database, and the database closes before its options and cache. Keep a Cache alive for as long as any database that uses it is open.

Database Maintenance

string stats = db.PropertyValue("leveldb.stats");   // also "leveldb.num-files-at-level<N>"

// With the database closed:
DB.Repair(@"C:\Data\cities");    // recovers what it can from a database that no longer opens, and can lose data
DB.Destroy(@"C:\Data\cities");   // deletes the database

Domains

Every folder of Sphere10.Framework.Windows.LevelDB is a domain with its own README, which lists all of its public types.

Domain What it provides Source
Resources Holds the 32-bit and 64-bit native LevelDB.dll builds that the project embeds as resources. source

Project root

Types declared in the project folder itself:

Type Kind Purpose
Cache class Native LRU block cache of a fixed byte capacity, assigned through Options.Cache
Comparator class Named custom key order built from an IComparer<NativeArray> or Comparison<NativeArray>, assigned through Options.Comparator
CompressionLevel enum Block compression choice: NoCompression or SnappyCompression
DB class Open LevelDB database with string and byte-array Put, Get, Delete, batch Write, iterators, snapshots, properties and static Repair and Destroy
Env class Handle to LevelDB's default operating-system environment for file and background work, assigned through Options.Env
Iterator class Cursor over entries in key order with Seek, SeekToFirst, SeekToLast, Next, Prev and key and value accessors
LevelDBException class Error reported by the native library, raised by Check when a call returns an error pointer
LevelDBHandle abstract class Disposable base for every wrapper that owns a native handle and frees it in FreeUnManagedObjects
LevelDBInterop static class P/Invoke declarations for the LevelDB C API, with a static constructor that extracts and loads the embedded x86 or x64 LevelDB.dll
Options class Database open settings such as CreateIfMissing, buffer and block sizes, compression, cache, comparator and environment
ReadOptions class Read settings for checksum verification, cache filling and reading from a SnapShot
SnapShot class Immutable point-in-time view of a DB, released through its parent database when disposed
WriteBatch class Chainable list of puts and deletes that DB.Write applies atomically in order, with an Iterate callback walk
WriteOptions class Write settings, currently Sync, which flushes each write to disk before it completes

⚠️ Important Notes

  • Keys stay sorted. LevelDB's default comparator orders them byte by byte, and Options.Comparator can supply another order.
  • A DB is safe to use from several threads without external locking. LevelDB lets only one process open a database directory at a time.
  • Each wrapper owns a native handle. Dispose the DB, its iterators and snapshots, batches and option objects, or their finalizers release the handles later. Dispose iterators and snapshots before the DB that created them.
  • The native library loads only on Windows, and the package includes builds for x86 and x64 processes. In any other process architecture, such as ARM64, the first LevelDB call fails with a TypeInitializationException that wraps a PlatformNotSupportedException.
  • WriteBatch.Iterate reports each buffered put and delete to WriteBatch.PutCallback and WriteBatch.DeleteCallback delegates. Their key and value pointers are valid only during the callback.
  • LevelDB License Compliance: This package embeds LevelDB native binaries, which are distributed under LevelDB's BSD 3-Clause License - see the License Attribution section below.

📦 Dependencies

  • Sphere10 Framework: Core framework library
  • LevelDB: Native LevelDB database engine (BSD License), embedded as the LevelDB32.dll and LevelDB64.dll resources

📜 License Attribution

This package includes or uses the following third-party components:

LevelDB

  • License: BSD 3-Clause License
  • Source: https://github.com/google/leveldb
  • Notice: LevelDB is distributed under the BSD 3-Clause License, which permits redistribution in source and binary forms under the conditions in its LICENSE file.

For complete license details, see the LevelDB LICENSE file.

  • Sphere10.Framework.Windows.LevelDB.Tests - NUnit tests for opening, CRUD, iteration, enumeration, snapshots, batches, repair and database properties. Run them with dotnet test tests/Sphere10.Framework.Windows.LevelDB.Tests/Sphere10.Framework.Windows.LevelDB.Tests.csproj. Each test opens its database in a new folder under Sphere10.Framework.Windows.LevelDB.Tests in the user's temporary folder and deletes it afterwards.
  • Sphere10.Framework.Windows - Windows platform integration
Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed.  net11.0 is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
3.2.0 0 11/24/2026
3.2.0-ci.173.45375449609.1 0 11/24/2026
3.2.0-ci.171.45374063975.1 0 11/24/2026
3.2.0-ci.169.45350717665.1 0 11/24/2026
3.2.0-ci.168.45166918016.1 41 11/23/2026
3.2.0-ci.163.43664782937.1 64 11/15/2026
3.2.0-ci.160.43660265392.1 60 11/15/2026
3.2.0-ci.159.43537748063.1 68 11/14/2026
3.2.0-ci.158.43536665157.1 56 11/14/2026
3.2.0-ci.157.43350632870.1 65 11/13/2026
3.2.0-ci.156.43233095581.1 62 11/12/2026
3.1.2 163 9/9/2026
3.1.1 143 9/8/2026
3.1.0 129 9/7/2026
3.0.3 198 1/6/2026
3.0.2 163 1/2/2026
3.0.1 160 1/2/2026
3.0.0 151 1/2/2026