# Files — Administrator & Developer Guide

This guide is for the people who deploy, secure, build, and extend **Files** — IT
administrators rolling it out across a fleet, security teams assessing its surface,
and developers who want to understand or contribute to the codebase. It documents the
architecture, the multi-process model, build requirements, configuration internals,
security posture, packaging and deployment, telemetry, and developer internals.

For end-user features and workflows, see the companion **User Guide**.

> [!NOTE]
> Files is a **client-side Windows desktop application**. It is not a server, has no
> listening network service, no multi-user backend, and no remote-management API. The
> "operations" concerns here are those of a desktop app: packaging, per-user
> configuration, OS integration, and update management.

---

## Table of Contents

1. [Executive Summary](#1-executive-summary)
2. [Architecture](#2-architecture)
3. [Process & Component Model](#3-process--component-model)
4. [Repository Structure](#4-repository-structure)
5. [System Requirements](#5-system-requirements)
6. [Dependencies](#6-dependencies)
7. [Building from Source](#7-building-from-source)
8. [Distribution & Packaging](#8-distribution--packaging)
9. [Default File Manager Integration](#9-default-file-manager-integration)
10. [Configuration Internals](#10-configuration-internals)
11. [Storage & Interop Subsystems](#11-storage--interop-subsystems)
12. [Source Generators](#12-source-generators)
13. [Security Analysis](#13-security-analysis)
14. [Telemetry, Privacy & Crash Reporting](#14-telemetry-privacy--crash-reporting)
15. [Logging & Diagnostics](#15-logging--diagnostics)
16. [Performance](#16-performance)
17. [Enterprise Deployment](#17-enterprise-deployment)
18. [Testing](#18-testing)
19. [Extending & Contributing](#19-extending--contributing)
20. [Code Quality & Patterns](#20-code-quality--patterns)
21. [Potential Improvements](#21-potential-improvements)
22. [Quick Reference](#22-quick-reference)
23. [Appendices](#23-appendices)

---

## 1. Executive Summary

Files is a feature-rich file manager for Windows, built on **WinUI 3** and the
**Windows App SDK**. It is written predominantly in **C#** (targeting modern .NET),
with a small amount of **native C++** for low-level shell integration. The codebase
is organized as a Visual Studio solution of cooperating projects: a main WinUI
application, an out-of-process WinRT/COM server, a native launcher, two file-dialog
shell extensions, storage abstraction libraries, and a Roslyn source-generator
project.

Key facts at a glance:

| Property | Value |
|---|---|
| Primary language | C# (.NET, WinUI 3 / Windows App SDK) |
| Native components | C++ (launcher), C++/WinRT shell extensions |
| UI framework | WinUI 3 (`Microsoft.WindowsAppSDK` 2.1.3) |
| License | MIT |
| Platform | Windows 10 (1809+) / Windows 11 |
| Packaging | MSIX (Microsoft Store + sideload) |
| Distribution channels | Stable, Preview, Dev |
| Configuration | Per-user JSON + SQLite in app-local data |
| Crash reporting | Sentry (release builds) |
| Source repo | `https://github.com/files-community/Files` |

The architecture's defining trait is its **multi-process design**: the WinUI app does
not perform every privileged operation in-process. A companion server process hosts
WinRT activatable classes for operations that must run outside the packaged app's
sandbox, while a native launcher and two shell extensions integrate Files into the
Windows shell (default-file-manager behavior and the system Open/Save dialogs).

---

## 2. Architecture

### High-level diagram

```text
                       ┌─────────────────────────────────────────────┐
                       │              Windows Shell                   │
                       │  (Explorer "open folder", Open/Save dialogs) │
                       └───────────────┬──────────────┬──────────────┘
                                       │              │
                  files-dev: URI /     │              │  COM shell-extension
                  IShellWindows hook    │              │  activation
                                       ▼              ▼
        ┌──────────────────┐   ┌──────────────────────────────────────┐
        │ Files.App.Launcher│   │  Files.App.OpenDialog / SaveDialog   │
        │  (native C++ EXE) │   │  (shell extensions: file pickers)    │
        └─────────┬─────────┘   └──────────────────┬───────────────────┘
                  │ ShellExecute(files-dev:)         │ writes selection,
                  ▼                                  │ signals "FILEDIALOG" event
        ┌───────────────────────────────────────────▼───────────────────┐
        │                       Files.App  (WinUI 3)                      │
        │  App.xaml.cs → MainWindow → Shell panes → Layouts/ViewModels    │
        │  DI host (Microsoft.Extensions.Hosting + CommunityToolkit Ioc)  │
        │  Commands/Actions · Settings services · Storage services        │
        └───────────────┬───────────────────────────┬───────────────────┘
                         │ activates                  │ reads/writes
                         ▼                            ▼
        ┌──────────────────────────────┐   ┌────────────────────────────┐
        │      Files.App.Server         │   │  Per-user app data          │
        │ (out-of-proc WinRT/COM host;  │   │  settings/*.json, *.db,     │
        │  RoRegisterActivationFactories)│   │  thumbnail & icon caches    │
        └──────────────────────────────┘   └────────────────────────────┘

        Shared libraries used by Files.App:
          Files.Core.Storage · Files.App.Storage (incl. FTP, legacy native)
          Files.App.CsWin32 (Win32 projections) · Files.Shared (utilities)
          Files.Core.SourceGenerator (build-time codegen)
```

### Design principles

- **MVVM throughout.** Views (XAML) bind to ViewModels; services hold state and logic.
  `CommunityToolkit.Mvvm` provides `ObservableObject`, commands, and messaging.
- **Dependency injection.** The app builds a host at startup
  (`AppLifecycleHelper.ConfigureHost()`) and resolves services through
  `CommunityToolkit.Mvvm.DependencyInjection.Ioc.Default`. A few singletons
  (`QuickAccessManager`, `LibraryManager`, `FileTagsManager`, `AppModel`) are still
  resolved manually with a `// TODO: Replace with DI` note.
- **Command/Action pattern.** Every user operation is an `IAction` wrapped in an
  `IRichCommand` (label, description, glyph, hotkeys, executability). This is the
  backbone of the menus, the toolbar, the Command Palette, and the customizable
  keyboard shortcuts. See [Source Generators](#12-source-generators) and
  [Appendix C](#appendix-c--action-catalog).
- **Settings as typed services.** Each settings domain is a service exposing strongly
  typed properties over a JSON-backed store (see
  [Configuration Internals](#10-configuration-internals)).
- **Separation of privileged work.** Operations that need to run outside the packaged
  sandbox are hosted in `Files.App.Server`.

### Application lifecycle

`Files.App/App.xaml.cs` is the entry point. On launch (`OnLaunched`):

1. Reads activation arguments (normal launch vs. a Windows **startup task**).
2. Activates `MainWindow` and shows a splash screen (unless it's a background startup
   task with "keep running" enabled).
3. Configures the DI host and `Ioc.Default`.
4. Configures **Sentry** crash reporting if the build environment is not `Dev`.
5. Resolves manager singletons and hooks window events.
6. Creates the **system tray icon** (shown if `ShowSystemTrayIcon` is enabled).
7. Initializes app components asynchronously.

On close (`Window_Closed`), Files saves session tabs, optionally **keeps running in
the background** (`LeaveAppRunning`) by hiding the window and parking the instance on
a named semaphore (`Program.Pool`), preserves clipboard contents, and waits for
in-flight file operations to complete before final teardown. Unhandled exceptions
from the UI thread, the app domain, and the task scheduler are all routed to
`AppLifecycleHelper.HandleAppUnhandledException`.

---

## 3. Process & Component Model

Files is not a single executable. Understanding the cooperating processes is the key
to deploying and securing it.

### Files.App (WinUI 3 — the main app)

The packaged WinUI 3 application the user interacts with. Single-instance by design:
additional activations are routed into the running process (parked on a named
semaphore, `Files-{Environment}-Instance`), so opening many folders does not spawn
many processes.

### Files.App.Server (out-of-process WinRT/COM host)

`Files.App.Server/Program.cs` is a headless host that registers WinRT **activation
factories** via `RoRegisterActivationFactories` for every sealed public class in the
`Files.App.Server.*` namespace. It runs a multithreaded apartment, waits on an
`ExitSignalEvent`, and tears down its factories on exit. `AppInstanceMonitor` watches
the lifetime of the launching process(es) and signals the server to exit when the
last one closes.

This pattern lets the WinUI app activate components that need to run **outside the
app container** (full-trust / elevated operations that the packaged sandbox cannot
perform directly). First-chance exceptions in the server are logged to
`debug_server.log` in the app's local data folder.

### Files.App.Launcher (native C++)

`Files.App.Launcher/FilesLauncher.cpp` is a native Win32 `WinMain` executable that
implements the **"set Files as default file manager"** behavior:

- When Windows would open a folder, the launcher receives the request and routes it to
  Files via the `files-dev:` (per-channel) URI protocol, encoding the target path/
  selection as hex-escaped command arguments (`files-dev:?cmd=...`).
- It detects whether Files is still installed
  (`%LOCALAPPDATA%\Microsoft\WindowsApps\files-dev.exe`); if Files has been
  uninstalled, it **self-uninstalls** (re-imports `UnsetFilesAsDefault.reg`, removes
  its files) and **restores File Explorer**.
- It uses `IShellWindows` / `IShellBrowser` COM interfaces to reuse an existing shell
  window when appropriate, and special-cases shell locations (Recycle Bin, This PC,
  Network, "God Mode") that must still open in Explorer.

### Files.App.OpenDialog / Files.App.SaveDialog (shell extensions)

These projects implement shell extensions that let **Files act as the Open/Save file
picker** for other applications. When the dialog completes, the selection is written
to an output path and a named event (`"FILEDIALOG"`) is signaled to hand the result
back to the requesting app. (You can see the corresponding code in `App.xaml.cs`,
which writes selected item paths to `App.OutputPath` and sets the `FILEDIALOG` event
on close.)

### Supporting libraries

| Project | Role |
|---|---|
| `Files.Core.Storage` | Storage abstraction contracts/storables (built on `OwlCore.Storage`) |
| `Files.App.Storage` | Concrete storage: Windows native, **FTP** (FluentFTP), legacy native storage, managers (taskbar, etc.) |
| `Files.App.CsWin32` | Generated Win32 P/Invoke projections (CsWin32) |
| `Files.App.Controls` | Custom WinUI controls (Omnibar, BreadcrumbBar, Sidebar, Toolbar, ThemedIcon, StorageRing…) |
| `Files.App.BackgroundTasks` | Background task entry points |
| `Files.Shared` | Cross-cutting utilities, attributes, logging |
| `Files.Core.SourceGenerator` | Build-time Roslyn source generators |

---

## 4. Repository Structure

```text
Files/
├─ src/
│  ├─ Files.App/                 Main WinUI 3 application
│  │  ├─ App.xaml.cs             Entry point & lifecycle
│  │  ├─ Constants.cs            App-wide constants (paths, limits, URLs)
│  │  ├─ Actions/               166 IAction command implementations
│  │  │   ├─ FileSystem/         Copy, cut, delete, rename, create…
│  │  │   ├─ Navigation/         Tabs, panes, back/forward/up…
│  │  │   ├─ Open/               Settings, terminal, IDE, palette…
│  │  │   ├─ Content/            Archives, run-as, image, install…
│  │  │   ├─ Display/            Layout, sort, group
│  │  │   ├─ Show/               Toggle panes/sidebar/toolbar/hidden…
│  │  │   ├─ Git/                Clone, init, fetch, pull, push, sync
│  │  │   └─ Global/             Theme, search, undo/redo, fullscreen…
│  │  ├─ Data/
│  │  │   ├─ Commands/           IRichCommand, ActionCommand, HotKey infra
│  │  │   ├─ Models/             App/data models
│  │  │   ├─ Contracts/          Service interfaces (49 files)
│  │  │   ├─ Enums/              Option enums (57 files)
│  │  │   └─ Factories/          Item & menu factories
│  │  ├─ Services/
│  │  │   ├─ Settings/           Typed settings services (the config surface)
│  │  │   ├─ App/                App lifecycle & coordination services
│  │  │   ├─ Storage/            Storage-related services
│  │  │   ├─ DateTimeFormatter/  Locale-aware date formatting
│  │  │   └─ ...
│  │  ├─ ViewModels/             MVVM view models (Settings, Properties, Layouts…)
│  │  ├─ Views/                  XAML pages (Settings, Properties, Shells, Layouts)
│  │  ├─ UserControls/           Widgets, TabBar, StatusCenter, FilePreviews…
│  │  ├─ Utils/                  Storage, Shell, Cloud, Git, Serialization, Win32…
│  │  └─ Strings/                Localized resources (50+ languages via Crowdin)
│  ├─ Files.App.Server/          Out-of-process WinRT/COM host
│  ├─ Files.App.Launcher/        Native C++ default-file-manager launcher
│  ├─ Files.App.OpenDialog/      Open-dialog shell extension
│  ├─ Files.App.SaveDialog/      Save-dialog shell extension
│  ├─ Files.App.Controls/        Reusable WinUI controls
│  ├─ Files.App.CsWin32/         Win32 interop projections
│  ├─ Files.App.Storage/         Storage implementations (native, FTP, legacy)
│  ├─ Files.Core.Storage/        Storage abstraction contracts
│  ├─ Files.Core.SourceGenerator/Roslyn generators
│  └─ Files.Shared/              Shared utilities & attributes
├─ tests/
│  ├─ Files.App.UITests/         UI tests (Appium/WinAppDriver, Axe accessibility)
│  └─ Files.InteractionTests/    Interaction tests
└─ Directory.Packages.props      Central NuGet package version management
```

> [!NOTE]
> Localization lives under `Files.App/Strings/<locale>/` with 50+ language folders,
> managed through Crowdin (`https://crowdin.com/project/files-app`). Contributors
> should not edit non-`en-US` strings by hand — they are synchronized from Crowdin.

---

## 5. System Requirements

| Requirement | Detail |
|---|---|
| Operating system | Windows 10 version 1809 (build 17763) or later; Windows 11 recommended |
| Architecture | x64 / ARM64 (per MSIX package) |
| Runtime | Windows App Runtime (Windows App SDK 2.1.x) — bundled/required |
| .NET | Modern .NET runtime (packaged with the app) |
| Disk | Modest; thumbnail/icon caches grow with use |
| Optional | WSL (for the WSL sidebar), Git remote access (for Git features), a terminal app (for "Open terminal") |

> [!IMPORTANT]
> Files depends on the **Windows App Runtime**. If it is missing or broken, Files
> fails fast with a hardcoded startup error ("A required Windows component could not be
> loaded…") because the resource-loading system itself may be unavailable at that
> point. Reinstalling from the Store or the official download repairs it.

Windows 11 gets the fullest experience (default font *Segoe UI Variable*, newer shell
integrations). On Windows 10, some features are slower and the standard font falls back
to *Segoe UI* (`Constants.Appearance.StandardFont`).

---

## 6. Dependencies

Package versions are centrally managed in `Directory.Packages.props`. The most
significant runtime dependencies and their roles:

| Package | Version | Role |
|---|---|---|
| `Microsoft.WindowsAppSDK` | 2.1.3 | WinUI 3 / Windows App SDK foundation |
| `Microsoft.Windows.CsWinRT` | 2.2.0 | C#/WinRT projections |
| `Microsoft.Windows.CsWin32` | 0.3.264 | Source-generated Win32 P/Invoke |
| `CommunityToolkit.Mvvm` | 8.4.0 | MVVM (ObservableObject, commands, Ioc, messaging) |
| `CommunityToolkit.WinUI.*` | 8.2.x | WinUI controls, behaviors, converters, color picker, settings controls |
| `Microsoft.Extensions.Hosting` | 10.0.2 | Generic host / DI container |
| `Microsoft.Extensions.DependencyInjection` / `.Logging` | 10.0.2 | DI & logging abstractions |
| `LibGit2Sharp` | 0.30.0 | Embedded Git engine (clone/fetch/pull/push…) |
| `FluentFTP` | 53.0.2 | FTP/FTPS client |
| `SevenZipSharp` | 1.0.2 | 7-Zip archive support |
| `SharpZipLib` | 1.4.2 | Zip/compression support |
| `DiscUtils.Udf` | 0.16.13 | Disc-image (UDF/ISO) reading |
| `TagLibSharp` | 2.3.0 | Media metadata for previews/details |
| `Microsoft.Data.Sqlite.Core` + `SQLitePCLRaw.bundle_green` | 10.0.2 / 2.1.11 | SQLite for file-tag storage |
| `System.IO.Hashing` | — | File hash/checksum computation |
| `Vanara.Windows.Shell` / `Vanara.Windows.Extensions` | 4.0.1 | Windows shell interop |
| `Microsoft.Management.Infrastructure` | 3.0.0 | WMI/CIM (drive & device events) |
| `Microsoft.Graphics.Win2D` | 1.3.2 | 2D graphics rendering |
| `WinUIEx` | 2.9.0 | WinUI window extensions |
| `Sentry` | 6.0.0 | Crash reporting (release only) |
| `Tulpep.ActiveDirectoryObjectPicker` | 3.0.11 | The object picker used in the Security/ACL editor |
| `ByteSize`, `MessageFormat`, `UTF.Unknown`, `ColorCode.WinUI` | — | Size formatting, ICU message formatting, charset detection, syntax highlighting |

Build/test-only dependencies include `Microsoft.CodeAnalysis.*` (source generators),
`PolySharp`, `Appium.WebDriver`, `Axe.Windows` (accessibility testing), and
`MSTest.*`.

> [!NOTE]
> Several capabilities users perceive as "built into Files" are actually these
> libraries: **Git** is LibGit2Sharp, **FTP** is FluentFTP, **archives** are
> SevenZipSharp/SharpZipLib, **media details** are TagLibSharp, and the **ACL object
> picker** is Tulpep's Active Directory picker. When triaging a bug in one of these
> areas, check the library first.

---

## 7. Building from Source

> [!IMPORTANT]
> This is an overview for contributors. The repository's own contributor docs are the
> authoritative, version-current source for the exact toolchain and steps.

### Prerequisites

- **Visual Studio 2022** (latest) with the workloads:
  - .NET Desktop Development
  - Universal Windows Platform / Windows App SDK (C++ and C# tooling)
  - Desktop development with C++ (for `Files.App.Launcher` and the C++/WinRT dialogs)
- **Windows App SDK** components matching `Microsoft.WindowsAppSDK` 2.1.3.
- A modern **.NET SDK** matching the projects' target framework.
- Windows SDK build tools (`Microsoft.Windows.SDK.BuildTools` 10.0.28000.x).

### Build steps (typical)

```text
1. git clone https://github.com/files-community/Files
2. Open the solution in Visual Studio 2022.
3. Select the build configuration:
     - Debug | Dev      → the FilesDev channel (files-dev: protocol)
     - Release | …      → Stable/Preview channels
   and platform (x64 / ARM64).
4. Set the packaging project (Files.App) as the startup project.
5. Build & deploy (F5). The MSIX is built and sideloaded for debugging.
```

### CI-injected secrets

Three constants in `Constants.AutomatedWorkflowInjectionKeys` are placeholders
replaced by the Files CI pipeline at build time:

| Placeholder | Purpose |
|---|---|
| `githubclientid.secret` | GitHub OAuth client ID (Git sign-in) |
| `bingmapskey.secret` | Bing Maps key (location features) |
| `sentry.secret` | Sentry DSN (crash reporting) |

Local developer builds run without these secrets; the dependent features degrade
gracefully (no Sentry in `Dev`, no GitHub sign-in, etc.).

---

## 8. Distribution & Packaging

Files ships as **MSIX** packages across three channels. Each channel is a distinct
package with its own identity, app tiles, and protocol, so they coexist on one
machine.

| Channel | Known package/app names (`Constants.Distributions`) | Source |
|---|---|---|
| **Stable (Store)** | `49306atecsolution.FilesUWP` | Microsoft Store |
| **Stable (sideload)** | `FilesStable` | `files.community/download` |
| **Preview (Store)** | `49306atecsolution.FilesPreview` | Microsoft Store |
| **Preview (sideload)** | `FilesPreview` | `files.community/download` |
| **Dev** | `FilesDev` | Local build |

App-tile assets are organized per channel under
`Files.App/Assets/AppTiles/{Dev,Preview,Release}/` (including high-contrast variants).

### Update model

- **Store** packages update through the Microsoft Store automatically.
- **Sideloaded** packages are updated by installing a newer signed MSIX. Files also
  performs an in-app update check (`AppLifecycleHelper.CheckAppUpdate()`), surfacing
  available updates to the user.

---

## 9. Default File Manager Integration

Files can register itself as the system's default file manager. The mechanism:

1. Files installs the native **launcher** (`Files.App.Launcher`) and registry entries
   that route Explorer "open folder" requests to it.
2. The launcher encodes the requested path/selection and invokes Files via the
   channel's URI protocol (`files-dev:` for Dev, the channel-specific protocol for
   Stable/Preview).
3. Certain shell locations are deliberately **excluded** and always open in Explorer:
   Recycle Bin, This PC, Network, and the "God Mode" control-panel CLSID — because
   Files does not host those special views.
4. On **uninstall**, the launcher detects that Files is gone and runs
   `UnsetFilesAsDefault.reg` (with an elevation prompt) to **restore File Explorer**,
   then removes itself.

> [!CAUTION]
> Registering an alternate default file manager modifies shell behavior for the user.
> In managed environments, validate that this integration is acceptable per policy.
> The unset path requires elevation (`runas`) to import the restoring `.reg` file.

---

## 10. Configuration Internals

### Where settings live

All configuration is **per-user** under the packaged app's local data folder:

```text
%LOCALAPPDATA%\Packages\<PackageFamilyName>\LocalState\settings\
    user_settings.json        ← user preferences (the settings surface)
    filetags.json             ← file tags (default: Home, Work, Photos, Important)
    user_settings.db          ← settings database companion
    filetags.db               ← file-tags database companion
```

These names are defined in `Constants.LocalSettings`. The settings folder name is
`settings`.

### How settings work

The configuration system is a set of **typed settings services**, each extending
`BaseObservableJsonSettings` over a JSON-backed, cached database
(`CachingJsonSettingsDatabase` → `DefaultJsonSettingsDatabase`). Each property looks
like:

```csharp
public bool ShowHiddenItems
{
    get => Get(false);   // default supplied inline
    set => Set(value);   // persisted to user_settings.json
}
```

This means the **default value is the literal passed to `Get(...)`**, and the JSON key
is the property name. Settings raise `SettingChangedEventArgs` so the UI updates
reactively.

The umbrella `IUserSettingsService` (`UserSettingsService`) lazily exposes the domain
services:

| Service | Domain |
|---|---|
| `GeneralSettingsService` | Startup, widgets, sidebar sections, context-menu items, archive defaults, tray/background-running |
| `FoldersSettingsService` | Hidden/system/dot files, single-click modes, thumbnails, extensions, delete confirmation, size units |
| `AppearanceSettingsService` | Theme, backdrop material, background image, accent colors, toolbar/status bar, sidebar width |
| `LayoutSettingsService` | Default layout/sort/group, column visibility & widths, per-view sizes |
| `InfoPaneSettingsService` | Preview-pane enablement, tab, sizes, media volume |
| `ApplicationSettingsService` | Prompt/one-time flags (review, sponsor, admin, ADS hidden) |
| `AppSettingsService` | Misc app flags (teaching tips, background-running notice, restore tabs) |
| `ActionsSettingsService` | Custom keyboard-shortcut overrides (`ActionsV2`) |
| `FileTagsSettingsService` | Tag definitions (separate JSON + DB) |
| `DevToolsSettingsService` | IDE path/name, "Open in IDE" scope |

### Export / import & migration

- `UserSettingsService.ExportSettings()` serializes settings to JSON, **excluding
  session-only data** (`LastSessionTabList`, `LastCrashedTabList`, `PathHistoryList`,
  `PreviousSearchQueriesList`, `PreviousArchiveExtractionLocations`).
- `ImportSettings()` merges an imported dictionary and raises change events for each
  key.
- `FoldersSettingsService` performs a one-time **legacy migration**
  (`MigrateLegacySingleClickSettings`) from the old `OpenItemsWithOneClick` /
  `OpenFoldersWithOneClick` keys to the new `SingleClickOpenMode` enum, then removes
  the obsolete keys so subsequent launches no-op.

A full settings reference (keys + defaults) is in the **User Guide**;
[Appendix A](#appendix-a--configuration-file-locations) summarizes file locations.

---

## 11. Storage & Interop Subsystems

### Storage abstraction

`Files.Core.Storage` defines storage **contracts and storables** (built atop
`OwlCore.Storage`), and `Files.App.Storage` provides concrete implementations:

- **Windows native storage** — the default path for local files/folders, with
  helpers and managers (e.g., `TaskbarManager` for taskbar progress via `ITaskbarList3`).
- **FTP** (`Files.App.Storage/Ftp/`) — remote browsing via FluentFTP.
- **Legacy native storage** (`Files.App.Storage/Legacy/`) — older code paths retained
  for compatibility (home folder, native storage legacy).

### Win32 / shell interop

- `Files.App.CsWin32` holds CsWin32-generated P/Invoke signatures; the app calls Win32
  APIs directly (e.g., `CreateFileFromApp`, `CreateDirectoryFromApp`,
  object picker, ACL APIs, taskbar COM).
- The Security/ACL editor (`ViewModels/Properties/Security*ViewModel.cs`) reads and
  writes NTFS ACLs through an `IStorageSecurityService`, using the Active Directory
  **object picker** to select principals and Win32 calls to add/remove ACEs and change
  ownership.
- **WMI/CIM** (`Microsoft.Management.Infrastructure`) powers device/drive watch events
  (`EventArrivedEventArgs` wraps `CimSubscriptionResult`).

### Cloud & WSL detection

- `Utils/Cloud/Detector/` implements `ICloudDetector` (abstract base
  `AbstractCloudDetector`) to enumerate installed cloud providers asynchronously.
- WSL distributions are detected and rendered with per-distro icons
  (`Constants.WslIconsPaths`).

---

## 12. Source Generators

`Files.Core.SourceGenerator` is a Roslyn incremental-generator project that produces
code at build time. Two notable generators:

- **CommandManagerGenerator** — generates the `CommandCodes` enum and command-manager
  wiring from the `IAction` implementations. This is why there is no hand-written
  `CommandCodes.cs`: the command registry is derived from the action classes
  themselves, keeping the enum and the actions in sync automatically.
- **RegistrySerializationGenerator** — for classes annotated with
  `[RegistrySerializable]`, generates `BindValues`/`SaveValues` methods that
  round-trip the object's properties to/from the **Windows Registry** (mapping C#
  types to `RegistryValueKind`, honoring `[RegistryIgnore]`, and recursing into nested
  types). This underpins registry-backed configuration/integration without manual
  serialization code.

> [!NOTE]
> Because of source generation, a static AST scan of the repository will *under-report*
> the command surface — the full list of `CommandCodes` only exists after a build. The
> authoritative human-readable list is the set of files under `Files.App/Actions/`
> (see [Appendix C](#appendix-c--action-catalog)).

---

## 13. Security Analysis

Files is a local desktop app, so the security model is about **local privilege,
filesystem access, and OS integration**, not network exposure.

### Attack surface — what Files does *not* expose

- **No listening network service.** Files does not open inbound sockets or run a
  server users connect to. The `Files.App.Server` process is a **local** WinRT/COM
  activation host, not a network server.
- **No authentication backend, no multi-tenant data.** Configuration is per-user.
- **Outbound network only**, and only for opt-in features: Git remotes (LibGit2Sharp),
  FTP servers you connect to (FluentFTP), cloud-provider detection, update checks, and
  crash reporting (Sentry, release builds).

### Elevation & privileged operations

| Operation | Privilege note |
|---|---|
| Run as administrator / another user | Launches a target process elevated / under another account (user-initiated) |
| Set/unset default file manager | The unset path uses `ShellExecute(..., "runas", ...)` to import a `.reg` (UAC prompt) |
| Edit NTFS permissions / take ownership | Requires the caller to have rights; otherwise shows access-denied and suggests taking ownership |
| `Files.App.Server` activations | Hosts operations that must run outside the app sandbox (potential full-trust) |
| Install certificate / font / `.inf` driver | Driver/cert installs are privileged Windows operations |

> [!WARNING]
> The default-file-manager **unset** path and certain installs trigger UAC elevation
> and modify machine/registry state. In locked-down environments, restrict or audit
> these via application control and standard-user policies. Driver (`.inf`) and
> certificate installation should be treated as high-impact actions.

### Filesystem & data handling

- Settings are written with Win32 file APIs (`CreateFileFromApp`,
  `WriteStringToFile`); invalid JSON in the settings file is handled defensively
  (falls back to defaults rather than crashing).
- **Alternate data streams** can be created/shown only when the corresponding settings
  are enabled (off by default), since ADS is an advanced/abuse-prone NTFS feature.
- Clipboard contents are preserved across app close only for Files' own data package.

### Secrets

- Sentry DSN, GitHub client ID, and Bing Maps key are **build-time injected**
  (`Constants.AutomatedWorkflowInjectionKeys`). They are not user secrets and not
  stored in user configuration. Forks/local builds run without them.

### Recommendations for administrators

- Decide whether the **default-file-manager** integration and **ADS/driver/cert**
  actions are permitted; gate with policy if not.
- For privacy-sensitive deployments, communicate the **Sentry** crash-reporting
  behavior (release builds) and point users at the privacy policy
  (`files.community/privacy`).
- Prefer **Store** distribution for managed fleets (signed, auto-updating, MSIX
  isolation).

---

## 14. Telemetry, Privacy & Crash Reporting

- **Crash reporting via Sentry** is configured at startup **only when the build
  environment is not `Dev`** (`AppLifecycleHelper.ConfigureSentry()`), i.e., in
  Stable/Preview release builds. The Sentry DSN is CI-injected (`sentry.secret`).
- There is commented-out support for action **metrics** (Sentry metrics increment per
  executed command) in `ActionCommand.ExecuteAsync` — currently disabled
  ("Re-enable when Metrics feature is available again"), so per-command usage metrics
  are **not** being sent.
- The privacy policy is published at `https://files.community/privacy`
  (`Constants.ExternalUrl.PrivacyPolicyUrl`).

> [!IMPORTANT]
> If your organization disallows third-party crash telemetry, evaluate this before a
> broad rollout. Dev builds do not initialize Sentry at all.

---

## 15. Logging & Diagnostics

- The app uses `Microsoft.Extensions.Logging` (`ILogger`), with informational logs at
  key lifecycle points (launch, activation, window activation).
- Users can open the in-app **log file** (`Ctrl`+`.`) and its **location**
  (`Ctrl`+`Shift`+`.`) — useful when filing bug reports.
- `Files.App.Server` writes first-chance exceptions to `debug_server.log` in the app's
  local folder.
- Unhandled exceptions across the UI thread, app domain, and task scheduler are
  centrally handled, enabling crash capture and (in release) Sentry reporting.

---

## 16. Performance

Files exposes several knobs that materially affect responsiveness, especially on large
folders or slower hardware:

| Setting | Effect |
|---|---|
| `EnableThumbnailCache` / `ThumbnailCacheSizeLimit` | Cache thumbnails to avoid recomputation; cap cache size |
| `EnableSmoothScrolling` | Animated scrolling — disable on slow GPUs/Windows 10 |
| `CalculateFolderSizes` | Computing folder sizes is expensive on deep trees (off by default) |
| `ShowThumbnails` | Disable to speed up listing of media-heavy folders |
| Layout choice | List/Details are lighter than Grid/Cards for huge folders |

Built-in limits guard against pathological inputs (`Constants.PreviewPane`): text
previews cap at 10,000 characters, PDF previews at 10 pages, and unknown-extension
"try as text" at ~500 KB. Drive widgets warn at **90%** fullness
(`Constants.Widgets.Drives.LowStorageSpacePercentageThreshold`).

> [!TIP]
> On Windows 10, the combination of disabling smooth scrolling + folder-size
> calculation + thumbnails (for problem folders) addresses most reported sluggishness
> (see User Guide troubleshooting, issue #18536).

---

## 17. Enterprise Deployment

Files is an MSIX app and deploys with standard Windows app-management tooling.

- **Microsoft Store for Business / Intune (Store app):** assign the Store package to
  users/devices. Updates are automatic. This is the recommended path for managed
  fleets (signed, sandboxed, auto-updating).
- **Sideloaded MSIX:** distribute the signed `.msix`/`.msixbundle` via Intune (line-of-
  business app), SCCM, or `Add-AppxPackage`. You manage updates by pushing new
  packages. Ensure your tenant trusts the signing certificate.
- **Per-user configuration:** settings live under each user's `LocalState` (see
  [Configuration Internals](#10-configuration-internals)). To pre-seed defaults,
  stage a `user_settings.json` in the appropriate `LocalState\settings\` path as part
  of provisioning.

> [!NOTE]
> Files has **no ADMX/Group Policy templates** and no built-in MDM configuration
> channel. Centralized configuration is achieved by managing the per-user JSON files,
> not via policy keys. Plan provisioning accordingly.

### Policy considerations

- Decide whether to allow the **default-file-manager** integration (it alters shell
  behavior and the unset path needs elevation).
- Decide whether **driver/certificate install** and **ADS** actions are acceptable;
  there is no app-level switch to remove them beyond the context-menu visibility
  toggles, so gate with application control if strict.

---

## 18. Testing

| Project | Stack | Purpose |
|---|---|---|
| `Files.App.UITests` | Appium / WinAppDriver, `Axe.Windows`, MSTest | UI automation and **accessibility** auditing (Axe) |
| `Files.InteractionTests` | MSTest, helpers | Interaction-level tests of app behavior |

The presence of a test project under `tests/` does not mean the C# AST tooling will
report test coverage — these are WinUI/desktop UI tests driven through automation
frameworks, and they require a built, deployed app to run.

> [!TIP]
> Commands expose an `AutomationName` and `AutomationId` (on `IRichCommand`)
> specifically so UI tests can locate and invoke them deterministically. When adding a
> new action, set a stable automation ID.

---

## 19. Extending & Contributing

### Adding a command (action)

1. Create a class under `Files.App/Actions/<Category>/` implementing `IAction` (or
   `IToggleAction` for on/off commands).
2. Provide `Label`, `Description`, `Glyph` (a `RichGlyph`), and — optionally — default
   hotkeys via `HotKey` / `SecondHotKey` / `ThirdHotKey` / `MediaHotKey`.
3. Implement `ExecuteAsync` and `IsExecutable`.
4. The **CommandManagerGenerator** picks it up at build time and adds it to
   `CommandCodes`, the Command Palette, and the keyboard-shortcut settings
   automatically — no manual registration.

### Other extension points

- **Custom controls** live in `Files.App.Controls` (Omnibar, Sidebar, Toolbar,
  ThemedIcon, etc.) and are reusable.
- **Registry-backed types** can opt into generated serialization with
  `[RegistrySerializable]` / `[RegistryIgnore]`.
- **Localization** is contributed through Crowdin, not direct PRs to non-`en-US`
  strings.

### Contribution workflow

The project uses GitHub with issue templates for bugs
(`...issues/new?...template=bug_report.yml`) and features
(`...template=feature_request.yml`), and a community Discord (`discord.gg/files`).
Follow the repository's `CONTRIBUTING` guidance and coding conventions (the codebase
consistently uses MVVM, `CommunityToolkit.Mvvm` primitives, file-scoped namespaces in
newer files, and the `IAction`/`IRichCommand` command pattern).

---

## 20. Code Quality & Patterns

Observed conventions across the codebase:

- **MVVM + DI** end to end; services behind interfaces in `Data/Contracts/`.
- **Command pattern** with a rich command abstraction (`IRichCommand`) that unifies
  label, description, glyph, hotkeys, toggle state, executability, and automation IDs
  — and supports **modifier-aware commands** (`ModifiableCommand` dispatches to a
  different command depending on held key modifiers) and a null-object
  (`NoneCommand`).
- **Strongly typed settings** with inline defaults, change notifications, and
  one-time migrations.
- **Defensive interop**: `SafetyExtensions.IgnoreExceptions`, timeouts
  (`WithTimeoutAsync`), and `DispatcherQueue` fallbacks for WinUI threading quirks
  (`EnqueueOrInvokeAsync` invokes directly when the dispatcher is unexpectedly null).
- **Source generation** to eliminate boilerplate and keep the command registry and
  registry serialization in sync with their sources.
- **Localized everything**: user-facing strings flow through
  `Strings.*.GetLocalizedResource()`.

Notable inline TODOs and workarounds (good first issues / cleanup candidates): the
manual-singleton `// TODO: Replace with DI` managers in `App.xaml.cs`; the
`#10110` flyout-close crash workaround in `Window_Closed`; the disabled action-metrics
code in `ActionCommand`.

---

## 21. Potential Improvements

Derived from the code and the issue tracker — candidate areas for maintainers:

- **Finish the DI migration.** Move `QuickAccessManager`, `LibraryManager`,
  `FileTagsManager`, and `AppModel` off manual `Ioc.Default.GetRequiredService` into
  proper constructor injection (the code already flags this).
- **Re-enable usage metrics** behind a clear, opt-in privacy control (the metrics path
  is stubbed out).
- **Harden Grid-view rendering** (#18543) and **thumbnail/icon caching** (#14993,
  #18503) — recurring stability complaints.
- **Windows 10 performance pass** (#18536) — the experience diverges from Windows 11.
- **Resilient column-config loading** (#18528) — a bad saved layout should never block
  startup; load defensively like the settings JSON does.
- **Browsable non-ZIP containers** (#18533) — `.jar` and similar could open like
  `.zip`.
- **Auto-clear completed Status Center tasks** (#18523) — frequently requested.
- **Enterprise configuration** — ADMX/MDM policy support would make managed rollouts
  far easier than staging JSON files.

---

## 22. Quick Reference

### Key files

| File | Why it matters |
|---|---|
| `src/Files.App/App.xaml.cs` | Entry point, lifecycle, DI host, tray, background-running |
| `src/Files.App/Constants.cs` | Paths, limits, URLs, distribution names, startup error text |
| `src/Files.App/Services/Settings/*` | The entire configuration surface (typed, with defaults) |
| `src/Files.App/Actions/**` | The 166-command catalog (source of `CommandCodes`) |
| `src/Files.App/Data/Commands/*` | `IRichCommand` infrastructure & hotkey model |
| `src/Files.App.Server/Program.cs` | Out-of-process WinRT/COM activation host |
| `src/Files.App.Launcher/FilesLauncher.cpp` | Default-file-manager launcher (native) |
| `src/Files.Core.SourceGenerator/Generators/*` | Build-time codegen (commands, registry) |
| `Directory.Packages.props` | Central dependency versions |

### Key paths (per user)

| Path | Contents |
|---|---|
| `%LOCALAPPDATA%\Packages\<PFN>\LocalState\settings\user_settings.json` | Preferences |
| `…\LocalState\settings\filetags.json` | File tags |
| `…\LocalState\settings\*.db` | Settings/tags databases |
| `…\LocalState\debug_server.log` | Server first-chance exception log |

### External endpoints

| URL | Use |
|---|---|
| `https://github.com/files-community/Files` | Source, issues |
| `https://files.community/download` | Sideload downloads |
| `https://files.community/docs` | Documentation |
| `https://files.community/privacy` | Privacy policy |
| `https://discord.gg/files` | Community |
| `https://crowdin.com/project/files-app` | Localization |

---

## 23. Appendices

### Appendix A — Configuration File Locations

All under `%LOCALAPPDATA%\Packages\<PackageFamilyName>\LocalState\settings\`
(folder name `settings`, from `Constants.LocalSettings`):

| File | Purpose |
|---|---|
| `user_settings.json` | All user preferences (JSON, indented) |
| `filetags.json` | Tag definitions |
| `user_settings.db` | Settings companion database |
| `filetags.db` | File-tags companion database |

Session-only keys excluded from export: `LastSessionTabList`, `LastCrashedTabList`,
`PathHistoryList`, `PreviousSearchQueriesList`, `PreviousArchiveExtractionLocations`.

### Appendix B — Distribution Package Names

From `Constants.Distributions.KnownAppNames`:

| Name | Channel |
|---|---|
| `49306atecsolution.FilesUWP` | Store — Stable |
| `49306atecsolution.FilesPreview` | Store — Preview |
| `FilesStable` | Sideload — Stable |
| `FilesPreview` | Sideload — Preview |
| `FilesDev` | Dev build |

### Appendix C — Action Catalog

The user-facing command surface is implemented as 166 `IAction` classes under
`src/Files.App/Actions/`, grouped by category. (The generated `CommandCodes` enum
mirrors these.)

| Category | Representative actions |
|---|---|
| **FileSystem** | AddItem, CreateFile, CreateFolder, CreateFolderWithSelection, CreateShortcut(FromDialog), CreateAlternateDataStream, CopyItem, CutItem, PasteItem(AsShortcut/ToSelection), DeleteItem(Permanently), Rename, EmptyRecycleBin, Restore(All)RecycleBin, FormatDrive(FromHome/FromSidebar), FlattenFolder, OpenFileLocation, CopyPath/CopyItemPath(WithQuotes) |
| **Navigation** | NewTab, NewWindow, Close(Selected/All/Other/ToLeft/ToRight)Tab(s), Duplicate/ReopenClosedTab, Next/PreviousTab, Navigate(Back/Forward/Up/Home), SplitPane(Horizontally/Vertically), Arrange/Close/FocusOther Pane, OpenInNew(Tab/Window/Pane) (+FromHome/FromSidebar) |
| **Open** | OpenSettings(File), OpenCommandPalette, OpenProperties/OpenClassicProperties, OpenTerminal(AsAdmin/FromHome/FromSidebar), OpenInIDE/OpenRepoInIDE, EditInNotepad, CustomizeToolbar, OpenLogFile(Location), OpenReleaseNotes, OpenStorageSense(FromHome/FromSidebar) |
| **Content** | Compress(IntoArchive/Zip/SevenZip), Decompress(Here/Smart/ToChildFolder), RunAs(Admin/AnotherUser/WithPowershell), Rotate(Left/Right), SetAs(Wallpaper/Lockscreen/Slideshow/AppBackground), Install(Certificate/Font/InfDriver), Share, PlayAll, LaunchPreviewPopup, RefreshItems, Selection (SelectAll/Clear/Invert/ToggleSelect), Tags (OpenAllTagged/RemoveTags) |
| **Display** | Layout, Sort, Group, SortFilesFirst, SortFoldersFirst, SortFilesAndFoldersTogether |
| **Show** | Toggle (Sidebar, Toolbar, InfoPane, DetailsPane, PreviewPane, ShelfPane, DualPane, FilterHeader, ShowHiddenItems, ShowFileExtensions, DotFiles) |
| **Git** | Clone, Init, Fetch, Pull, Push, Sync |
| **Global** | Search, Undo, Redo, Toggle/Set(Light/Dark/Default)Theme, ToggleFullScreen, Toggle/Enter/ExitCompactOverlay, EditPath, OpenHelp |
| **Sidebar / Start / Shelf** | Pin/UnpinFolderToSidebar, CopyItemFromSidebar, PinToStart/UnpinFromStart, Copy/Cut/DeleteItemFromShelf |

Default keyboard bindings for these are tabulated in the **User Guide →
Keyboard Shortcut Catalog**.

### Appendix D — Key Constants & Limits

From `Constants`:

| Constant | Value |
|---|---|
| Sidebar width range | 180–500 px (default 255) |
| Preview text limit | 10,000 chars |
| Preview PDF page limit | 10 pages |
| Try-as-text size limit | ~500,000 bytes |
| Max selected items (some menus) | 5 |
| Drag-to-open hover | 1,300 ms |
| Drive low-space warning | 90% |
| Standard font | Segoe UI Variable (Win11) / Segoe UI (Win10) |

---

_Generated June 2026 from files-community/Files at a1ec014. AI-generated documentation. The library is checked by sampling (three repositories so far); this guide was not individually reviewed. Verify against the project before relying on it. Unofficial; not affiliated with or reviewed by the project._
