Storage

Microsoft::Xna::Framework::Storage — StorageDevice, StorageContainer, StorageDeviceNotConnectedException

ⓘ

Implementation status: implemented, and represented in full. All three Storage types are implemented — real std::filesystem I/O, a hand-written glob matcher for the pattern-based directory queries, and <root>/<displayName>/Player{N} save namespacing. All 35 documented Storage members of the XNA 4.0 runtime are represented in CNA’s member census (representation, not behaviour; see XNA Compatibility). The async Begin*/End* pairs are implemented synchronously, which is the correct behaviour on desktop. Errors use XNA’s exception types (System::ArgumentException, ArgumentNullException, ArgumentOutOfRangeException, InvalidOperationException, ObjectDisposedException, System::IO::IOException and its subclasses, UnauthorizedAccessException), not C++ standard exceptions. Container names and paths are contained (absolute paths, .. escapes and symlink escapes are rejected), and the storage root is resolved by a documented chain of environment variables rather than by SDL_GetPrefPath (on Android the first step reaches SDL indirectly, through Sharp Runtime's StoragePaths).

⚠

What the storage tests cover. This snapshot has seven Storage test sources with 70 GoogleTest-family definitions. They cover path containment (symlink escapes included), the XNA exception types and parameter names of its refusals, the Begin*/End* result contract, disposal, the lazily created storage root, DeleteContainer, file sharing, file and directory deletion, enumeration, and the StorageDeviceNotConnectedException serialization round trip. Their byte-level checks write and read back single bytes (an append, a refused open that must not truncate); no test round-trips a realistic save file, and the file-sharing matrix is skipped in browser builds. These are CNA’s tests, not run for this page. Test the filesystem behaviour your game depends on.

Overview

The Microsoft::Xna::Framework::Storage namespace provides a platform-independent abstraction for save-game and user-data persistence. On the original Xbox 360, StorageDevice represented a physical memory unit or hard drive, and device selection was presented to the player as a system UI. On PC, the selector returned immediately with the local user profile directory.

CNA preserves the full XNA 4.0 API shape, including the Begin/End asynchronous pattern, and backs it with genuine std::filesystem operations. StorageContainer maps to a real directory on the local filesystem and StorageDevice represents that location.

The async wrappers complete synchronously. This is a deliberate choice rather than a shortcut: the pattern exists in XNA because Xbox 360 storage selection could block on player interaction with a system UI, which has no desktop analogue. Local filesystem operations return fast enough that dispatching them to a thread would add latency and failure modes without adding responsiveness. Source-level XNA compatibility is preserved either way — your callback still fires and End* still returns the result.

⚠

On the web, saves persist in the browser. Under Emscripten CNA’s storage module links Emscripten’s IndexedDB file system (IDBFS) and mounts it at /cna-storage for StorageDevice and at /save for isolated storage, with automatic persistence; the stored data is restored before main() runs, so a StorageContainer written in one visit is there after a page reload. Two conditions: a threaded WebAssembly build keeps Emscripten’s WasmFS by default and needs -DCNA_EMSCRIPTEN_USE_WASMFS=OFF for this persistence, and if the mount fails StorageDevice throws StorageDeviceNotConnectedException instead of silently writing to memory. Browser storage is still per origin and can be cleared by the user, so treat it like any other web storage. (Source-verified; CNA records a reload test for one sample, which was not re-run here.)

Namespace members at a glance

Type Description Status
StorageDevice Represents a storage location (local disk). Obtained via the async selector. Implemented
StorageContainer Opened from a StorageDevice; provides file and directory access within a named save scope. Implemented
StorageDeviceNotConnectedException Thrown when a previously valid StorageDevice is no longer available. Implemented

StorageDevice

StorageDevice is the entry point into the storage system. On PC (and in CNA on all platforms) it represents the local filesystem. To obtain a device, use the static Begin/End async selector pattern. On a PC target the selector returns immediately with a device backed by the current user's profile directory.

Device selection (Begin/End pattern)

MethodDescription
StorageDevice::BeginShowSelector(callback, state) Starts the (synchronous on CNA) device-selection operation and returns a std::unique_ptr<System::IAsyncResult>. callback is a std::function<void(System::IAsyncResult*)> (may be empty) that has already run by the time the call returns; state is a void* passed through. Four overloads exist: (callback, state), (PlayerIndex, callback, state), (sizeInBytes, directoryCount, callback, state) and the combination. As in XNA, a player other than One–Four (or the shared value 255) and then a negative sizeInBytes throw System::ArgumentOutOfRangeException before the callback runs; otherwise the size and the unchecked directory count are ignored.
StorageDevice::EndShowSelector(result) Takes the IAsyncResult* (result.get()) and returns a std::unique_ptr<StorageDevice>. It never returns nullptr: a device is always available on CNA. A null result, or one that did not come from BeginShowSelector, throws System::ArgumentNullException; ending the same result twice throws System::InvalidOperationException. Choosing the overload with a PlayerIndex scopes the device’s containers to that player (see the layout below).

Opening a container

MethodDescription
device.BeginOpenContainer(name, callback, state) Begins opening a StorageContainer with the given display name; returns a std::unique_ptr<System::IAsyncResult> and, like the selector, completes before it returns. The container maps to a subdirectory within the device root. The name is not checked here: as in XNA, validation happens in EndOpenContainer.
device.EndOpenContainer(result) Takes result.get() and returns a std::unique_ptr<StorageContainer>, creating every missing directory of its path, the storage root included. The result is consumed even when this call fails, so a second End throws System::InvalidOperationException. An empty name throws System::ArgumentNullException; an absolute name or one that escapes the root throws System::ArgumentException, as does a result another device started; a file occupying any directory of the path throws System::IO::IOException (the file is kept), and a directory that cannot be created for lack of permission throws System::UnauthorizedAccessException. The caller should Dispose() the container when done (the destructor also disposes it); the device must outlive it.

Other StorageDevice members

MemberDescription
getIsConnectedProperty()Resolves and, if needed, creates the storage root; true when that succeeds, false when it fails. Never throws.
getFreeSpaceProperty(), getTotalSpaceProperty()std::filesystem::space of the root (available and capacity, as long long). Failure is reported as StorageDeviceNotConnectedException.
DeviceChangedThe static XNA event. It exists for source compatibility; nothing in CNA raises it, because the local device is always present.
DeleteContainer(titleName)As in XNA 4.0, removes only this device’s own folder of that title, <root>/<titleName>/Player{N} (or AllPlayers), with everything below it; another player’s folder and the title folder itself stay. A missing container, or a file of that name, is left alone and nothing is created; an empty name addresses the player folder at the root itself. Unlike XNA, an absolute or escaping name throws System::ArgumentException and deletes nothing. An entry that cannot be removed for lack of permission throws System::UnauthorizedAccessException, any other failure System::IO::IOException (read from StorageDevice.cpp and StorageContainer.cpp; not executed here).
StorageDevice::SetAppNameEXT(name) CNAEXTNames the application folder under the root (see below). It only records the name and creates nothing. Call it before the first container is opened.
StorageDevice::GetStorageRootEXT() CNAEXTReturns the resolved root as a UTF-8, forward-slash string (creating the directory), so a game can show or log where saves go. A root that cannot be resolved or created throws StorageDeviceNotConnectedException.

On-disk layout

Saves are namespaced on disk as <root>/<displayName>/Player{N}, matching XNA's own scheme:

  • <root> — the storage root the StorageDevice represents (next section).
  • <displayName> — the container name you pass to BeginOpenContainer.
  • Player{N} — the per-player subdirectory, derived from the PlayerIndex the device was selected for and numbered from one: PlayerIndex::One is Player1.
  • AllPlayers — used instead when the device was selected without a player (the (callback, state) overload).

The consequence is the one XNA intended: two players on the same machine writing to the same container name do not collide, and a container opened without a player index is shared across the title.

Where the root is: the persistence-path chain

The root is not SDL_GetPrefPath, and it does not depend on the selected windowing platform: the same policy applies under SDL3, HEADLESS and TERMINAL. It is resolved once, on first use, from the first of these that applies:

OrderConditionRoot
1Android buildthe current package’s app-private files directory, with <app> beneath it (Sharp Runtime’s isolated-storage policy, which at sharp-runtime 41b918c9 asks SDL for SDL_GetAndroidInternalStoragePath())
2XDG_DATA_HOME is set and non-empty$XDG_DATA_HOME/<app>
3LOCALAPPDATA is set%LOCALAPPDATA%\<app> (local, not roaming %APPDATA%)
4HOME is setmacOS: ~/Library/Application Support/<app>; elsewhere ~/.local/share/<app>
5none of the above./<app> in the current working directory

<app> is the literal string game unless the program calls StorageDevice::SetAppNameEXT("MyGame"). Nothing derives it from the window title or the executable name, so two CNA games that never call SetAppNameEXT share one folder. SetAppNameEXT discards the cached root (so call it before the first container is opened, or an earlier save stays under the old name) and also re-points Sharp Runtime’s isolated-storage root at <root>/.cna_isolated_storage. UTF-8 roots and names are handled on Windows by the root resolution and the container paths, but getIsConnectedProperty(), getFreeSpaceProperty() and getTotalSpaceProperty() still build narrow paths from the UTF-8 root, so with a non-ASCII root they may not resolve it correctly there. The root is created lazily, by the first storage access, and only a successful resolution is cached: an access that fails is retried by the next one. How a failure surfaces depends on the access. Opening a container creates the whole directory chain the way XNA’s DirectoryInfo.Create does, so a file in the way is a System::IO::IOException and a permission failure a System::UnauthorizedAccessException; the CNA extensions (GetStorageRootEXT(), the space properties) and Sharp Runtime’s isolated storage (once SetAppNameEXT has pointed it at this root) report StorageDeviceNotConnectedException instead. With none of the environment variables set and no working directory, there is no root at all: opening a container and the extensions throw StorageDeviceNotConnectedException, and getIsConnectedProperty() answers false (read from the source and CNA’s storage tests, not executed here).

Path containment

A StorageContainer is an authority boundary. A container name, and every file or directory path passed to a container, must be relative and must stay inside the container. An absolute path, a .. that climbs past the container root, or a path that resolves through a symlink to somewhere outside it throws System::ArgumentException; a final symlink whose target does not exist yet is followed to where a file would be created, so a dangling link cannot create a file outside either. XNA (through Path.Combine) would follow such paths; CNA refuses them deliberately. An empty file or directory argument throws System::ArgumentNullException with the parameter name file or directory, as in XNA, and an empty container name throws it from EndOpenContainer. A component the filesystem cannot inspect (no search permission, a symlink loop) is not treated as an escape: the operation fails with the filesystem’s own error, as XNA’s does. Code that passed "../other" or an absolute path to a container must be changed.

StorageContainer

StorageContainer provides file and directory access scoped to a named save context within a device. It implements the XNA 4.0 API. All paths passed to its methods are relative to the container root directory and are contained in it. The container also exposes getDisplayNameProperty(), getIsDisposedProperty(), getStorageDeviceProperty(), the Disposing event, and an idempotent Dispose(). After disposal, every file and directory method and the DisplayName and StorageDevice getters throw System::ObjectDisposedException, before they look at their arguments or touch the filesystem; getIsDisposedProperty() and a repeated Dispose() stay available, and files and already-open streams are kept.

File operations

MethodReturnsDescription
CreateFile(path) std::unique_ptr<System::IO::Stream> Creates (or replaces) the file and returns an exclusive read/write stream (FileMode::Create, FileAccess::ReadWrite, FileShare::None). While another stream holds the file without sharing, it throws System::IO::IOException and leaves the stored data untruncated.
OpenFile(path, mode) std::unique_ptr<System::IO::Stream> Opens or creates a file at path using the given System::IO::FileMode (Create, Open, OpenOrCreate, Append, Truncate). As in XNA, the two-argument form opens read/write (write-only for Append) and the two- and three-argument forms share nothing (FileShare::None). The four-argument form passes its FileShare to the native file: Windows enforces the access and share masks, POSIX systems take an advisory lock (exclusive for None, shared otherwise), and on a file system without locking, such as the browser’s, sharing is best-effort. A refused open throws System::IO::IOException. CNA records validation of this sharing on Linux; on Windows it is still pending platform validation. CNA’s storage module calls Sharp Runtime’s four-argument FileStream constructor, which sharp-runtime added in commit c6984ece (23 October 2026); older checkouts declare the same version 0.1.0 but lack it. The stream is a Sharp Runtime Stream: Read(buffer, offset, count), Write(buffer, offset, count), getLengthProperty(), Flush(), Close().
FileExists(path) bool Returns true if a regular file exists at path within the container; like XNA’s File.Exists, it answers false for any failure, such as a path beneath a file.
DeleteFile(path) void Deletes the file at path, with XNA’s File.Delete semantics: a missing file is a silent no-op, a missing parent directory throws System::IO::DirectoryNotFoundException, and a directory is refused with System::UnauthorizedAccessException and left in place.
GetFileNames() std::vector<std::string> Returns the names of all regular files in the container root (non-recursive). The order is the filesystem’s; sort if you need one. If the container’s directory has been removed meanwhile, it throws System::IO::DirectoryNotFoundException.
GetFileNames(pattern) std::vector<std::string> Returns file names matching a wildcard pattern (e.g. "*.sav"; * and ? are supported). An empty pattern returns no names without touching the filesystem, as in XNA.

Directory operations

MethodReturnsDescription
CreateDirectory(path) void Creates a subdirectory within the container (creates intermediate directories as needed; an existing directory is fine). A file in the way throws System::IO::IOException and is kept.
DeleteDirectory(path) void Removes the directory. The call is not recursive: an empty directory is removed; a non-empty one, or a path that names a file, throws System::IO::IOException and changes nothing; a missing one throws System::IO::DirectoryNotFoundException; a permission failure throws System::UnauthorizedAccessException.
DirectoryExists(path) bool Returns true if the directory exists within the container; false for any failure.
GetDirectoryNames() std::vector<std::string> Returns the names of all subdirectories in the container root (non-recursive; the order is the filesystem’s).
GetDirectoryNames(pattern) std::vector<std::string> Returns directory names matching a wildcard pattern (an empty pattern returns no names, as in XNA).

Pattern matching

The pattern-taking overloads are backed by a hand-written glob matcher rather than a delegation to the platform shell or a regex engine. That keeps wildcard semantics identical across every platform CNA builds for, instead of inheriting whatever the host's directory-enumeration API happens to do.

StorageDeviceNotConnectedException

StorageDeviceNotConnectedException is thrown when a StorageDevice that was previously valid is no longer accessible — on Xbox 360, for example, if a memory unit was ejected. In CNA, because storage always maps to the local filesystem, it is raised in four cases: no storage root can be resolved at all (no per-user data directory and no working directory), which also fails EndOpenContainer; GetStorageRootEXT() or Sharp Runtime’s isolated storage (after SetAppNameEXT) cannot create the root (“Unable to create the storage directory.”); getFreeSpaceProperty() / getTotalSpaceProperty() cannot query the root; and, in a browser build, the persistent browser storage is unavailable. The underlying filesystem error, where there is one, is attached as the inner exception. A root that cannot be created while a container is being opened is reported the way XNA reports it, as System::IO::IOException or System::UnauthorizedAccessException.

It derives from ExternalException, carries a human-readable message, and has a protected serialization constructor and a GetObjectData round trip (covered by four of the module’s tests). Catch it wherever you first touch the device if your application needs to handle an unusable save location gracefully; note that ordinary I/O errors and bad paths surface as XNA’s other exception types (System::ArgumentNullException for an empty name or path, System::ArgumentException for a contained-path violation, System::IO::IOException and its subclasses or System::UnauthorizedAccessException for I/O, System::ObjectDisposedException after disposal). All of them derive from std::exception, so what() works.

try {
    auto opening   = device->BeginOpenContainer("SaveData", nullptr, nullptr);
    auto container = device->EndOpenContainer(opening.get());
    // ... use container ...
    container->Dispose();
} catch (const StorageDeviceNotConnectedException& ex) {
    // Storage unavailable — no root could be resolved
    ShowErrorDialog(ex.what());
} catch (const System::IO::IOException& ex) {
    // A file occupies a directory of the container's path
    ShowErrorDialog(ex.what());
} catch (const System::UnauthorizedAccessException& ex) {
    // A directory of the container's path could not be created
    ShowErrorDialog(ex.what());
} catch (const System::ArgumentException& ex) {
    // The container name was empty (ArgumentNullException), absolute, or escaped the storage root
    ShowErrorDialog(ex.what());
}

IAsyncResult pattern

XNA 4.0 used the standard .NET IAsyncResult Begin/End async pattern so that storage operations could show system UI (device selector, container namer) without blocking the game loop. The pattern works as follows:

  1. Call the Begin* method, supplying an optional callback and state object. It returns a std::unique_ptr<System::IAsyncResult>.
  2. In the callback (or right after the call), pass result.get() to the matching End* method to retrieve the result.

In CNA, all storage operations complete synchronously: the Begin* call finishes its work, invokes your callback, and only then returns the IAsyncResult. The pattern is preserved so that XNA save-game code ports with little change, and synchronous completion is the correct semantics for a desktop filesystem — there is no system UI to wait on and no removable media to negotiate. As in XNA, End* throws System::ArgumentNullException for a null result or one produced by a different kind of Begin*, System::ArgumentException when EndOpenContainer is handed another device’s result, and System::InvalidOperationException when a result is ended a second time — including a result already ended inside its callback. A matching result is consumed even when its End* fails.

Code examples

These use the real signatures at this snapshot: results are owned by std::unique_ptr, End* takes result.get(), and stream lengths and reads use Sharp Runtime’s getLengthProperty() and Read/Write(buffer, offset, count) with SharpRuntime::bytecs buffers. For a complete, runnable save-slot program see Tutorial 141: Save Data Portably.

Saving a file

using namespace Microsoft::Xna::Framework::Storage;
using System::IO::FileMode;

// Obtain a StorageDevice (the Begin/End pair completes synchronously)
auto selection = StorageDevice::BeginShowSelector(nullptr, nullptr);
std::unique_ptr<StorageDevice> device = StorageDevice::EndShowSelector(selection.get());

// Open a container named after your save slot
auto opening   = device->BeginOpenContainer("Slot1", nullptr, nullptr);
auto container = device->EndOpenContainer(opening.get());

// Write a save file
if (!container->DirectoryExists("profile"))
    container->CreateDirectory("profile");

auto stream = container->OpenFile("profile/save.dat", FileMode::Create);
stream->Write(saveData.data(), 0, static_cast<SharpRuntime::intcs>(saveData.size()));
stream->Close();

container->Dispose();

Loading a file

auto opening   = device->BeginOpenContainer("Slot1", nullptr, nullptr);
auto container = device->EndOpenContainer(opening.get());

auto stream = container->OpenFile("profile/save.dat", FileMode::Open);

std::vector<SharpRuntime::bytecs> buffer(static_cast<std::size_t>(stream->getLengthProperty()));
stream->Read(buffer.data(), 0, static_cast<SharpRuntime::intcs>(buffer.size()));
stream->Close();

container->Dispose();

// Deserialise from buffer ...
LoadGameState(buffer);

Checking file existence before loading

auto opening   = device->BeginOpenContainer("Slot1", nullptr, nullptr);
auto container = device->EndOpenContainer(opening.get());

if (container->FileExists("profile/save.dat")) {
    auto stream = container->OpenFile("profile/save.dat", FileMode::Open);
    // ... read and deserialise ...
    stream->Close();
} else {
    // No save file found — start a new game
    StartNewGame();
}

container->Dispose();
ⓘ

Always call container->Dispose() when you are finished with a StorageContainer (or let the std::unique_ptr go out of scope: the destructor disposes it). On CNA this raises the Disposing event, and the container then refuses further use with System::ObjectDisposedException (streams you already opened stay usable until you close them); on Xbox 360 it was required to flush and unlock the device. Keeping containers open longer than necessary is discouraged.

StorageContainer details that affect save code

Three behaviours are easy to miss when XNA save code is ported; each was checked by reading StorageContainer.cpp at this snapshot (not executed). The internals are on the storage internals page.

Reading a save back completely

Stream::Read returns how many bytes it actually copied, which may be fewer than requested. Loop until the expected length is reached or a read returns 0, and treat a short result as a truncated save rather than parsing it:

std::unique_ptr<System::IO::Stream> in =
    container->OpenFile("savegame.dat", System::IO::FileMode::Open);
std::vector<SharpRuntime::bytecs> bytes(static_cast<std::size_t>(in->getLengthProperty()));

SharpRuntime::intcs offset = 0;
const auto total = static_cast<SharpRuntime::intcs>(bytes.size());
while (offset < total) {
    const SharpRuntime::intcs n = in->Read(bytes.data(), offset, total - offset);
    if (n == 0) break;          // end of file before the expected length
    offset += n;
}
if (offset != total) { /* reject a truncated save */ }

Syntax-checked with g++ -fsyntax-only against an earlier snapshot’s headers and a sibling sharp-runtime checkout; the calls it uses are unchanged at c6dec91f and at 3b43bd86. Not run.

Wildcard patterns, exactly

GetFileNames(pattern) and GetDirectoryNames(pattern) match each entry name at the container's top level (not recursively) against the whole pattern with CNA's own matcher: * matches any run of bytes, including none; ? matches exactly one byte, so a non-ASCII character, which is several UTF-8 bytes, needs several; every other byte, . included, matches only itself, case-sensitively on every host. There are no character classes and no escapes, and an empty pattern returns no names without touching the filesystem, as in XNA. "slot?.sav" therefore finds slot1.sav but not Slot1.SAV or slot10.sav. The storage tests match plain prefixes and suffixes ("*.bin", "directory-*") against non-ASCII names, not the matcher’s ? and case edge cases, so test the patterns your game depends on.

Disposal and concurrent writers

Dispose() sets IsDisposed and then raises Disposing once. From then on every file and directory method, and the DisplayName and StorageDevice getters, throw System::ObjectDisposedException before validating arguments or touching the filesystem, as XNA does; files on disk and streams opened earlier are kept. Sharing follows XNA’s defaults: CreateFile and the two- and three-argument OpenFile open with FileShare::None, so a second open of the same file fails with System::IO::IOException while the first is held, and a refused Create or Truncate open does not truncate the stored data first. The four-argument OpenFile applies the share mode you pass: Windows enforces it, POSIX systems use advisory locks, which only other processes that also lock respect, and the browser’s virtual file system makes no promise. CNA records this on Linux; Windows validation is still pending. Within one game, serialise saves rather than relying on locks.