To add license keys to a C# desktop app, check the key once at startup, before the main window opens. If the server refuses the key, show a small activation window. If the server can't be reached, let a customer who was checked recently keep working. And verify a signature on the server's answer, because an unsigned "valid" can be faked with a local server in minutes.
This guide builds all of that in one class you can use from WPF, WinForms or a console app.
What you need
- A free Licers account, with your app added as a product.
- Your public key and product id from the Integration page. The public key is safe to ship inside your app.
- .NET Framework 4.6.1 or later, or any version of .NET Core and .NET 5+.
dotnet add package Licers
The package has no other dependencies.
Step 1: One class that answers "may this run?"
Keep the rules in one place. This class checks the key, remembers it, and decides what happens when there is no internet.
using System;
using System.Globalization;
using System.IO;
using System.Threading.Tasks;
using Licers;
public static class LicenseGate
{
const int GraceDays = 7; // how long a checked customer may stay offline
static readonly LicenseClient Client = new LicenseClient("YOUR_PUBLIC_KEY", new ClientOptions
{
ProductId = "YOUR_PRODUCT_ID", // refuses keys for your other products
AppVersion = "2.4.1", // shows in Analytics
});
static readonly string Folder = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "MyApp");
static string KeyFile => Path.Combine(Folder, "license.txt");
static string SeenFile => Path.Combine(Folder, "checked.txt");
public static string SavedKey => File.Exists(KeyFile) ? File.ReadAllText(KeyFile).Trim() : "";
public static async Task<(bool ok, string message)> CheckAsync(string key)
{
key = (key ?? "").Trim();
if (key.Length == 0) return (false, "Enter your license key.");
try
{
var result = await Client.ValidateAsync(key).ConfigureAwait(false);
if (!result.Valid) return (false, result.Error ?? "This license is not valid.");
Directory.CreateDirectory(Folder);
File.WriteAllText(KeyFile, key);
File.WriteAllText(SeenFile, DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture));
return (true, "Licensed");
}
catch (NetworkException)
{
// Offline, or the server is down. That is not the same as unlicensed.
return key == SavedKey && CheckedRecently()
? (true, "Offline")
: (false, "Could not reach the license server. Check your connection and try again.");
}
catch (LicenseException e)
{
// A forged answer, or a key for another of your products.
return (false, e.Message);
}
}
static bool CheckedRecently()
{
if (!File.Exists(SeenFile)) return false;
if (!DateTime.TryParse(File.ReadAllText(SeenFile), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var seen)) return false;
var age = DateTime.UtcNow - seen;
return age >= TimeSpan.Zero && age < TimeSpan.FromDays(GraceDays);
}
}
Three results, three different reactions:
- Refused. The key is expired, revoked or on too many computers.
result.Errorsays which, in words you can reword in the dashboard. - Unreachable.
NetworkExceptionalso covers a server that answers with an error. Use the grace period. - Forged. A
SignatureExceptionis aLicenseException, so it ends in the last block. Nothing is unlocked.
Step 2: WPF
Remove StartupUri from App.xaml, so no window opens by itself, and open it after the check:
using System.Windows;
public partial class App : Application
{
protected override async void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
ShutdownMode = ShutdownMode.OnExplicitShutdown; // no window is open yet
var (ok, message) = await LicenseGate.CheckAsync(LicenseGate.SavedKey);
while (!ok)
{
var dialog = new ActivateWindow(message);
if (dialog.ShowDialog() != true) { Shutdown(); return; }
(ok, message) = await LicenseGate.CheckAsync(dialog.Key);
}
MainWindow = new MainWindow();
ShutdownMode = ShutdownMode.OnMainWindowClose;
MainWindow.Show();
}
}
ActivateWindow is a window with a text box, the message and an Activate button that sets Key and DialogResult = true.
Step 3: WinForms
The same idea in Program.cs. The check runs on a worker thread, so waiting for it can't deadlock the UI thread:
using System;
using System.Threading.Tasks;
using System.Windows.Forms;
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
string key = LicenseGate.SavedKey;
while (true)
{
var (ok, message) = Task.Run(() => LicenseGate.CheckAsync(key)).GetAwaiter().GetResult();
if (ok) break;
using (var dialog = new ActivateForm(message))
{
if (dialog.ShowDialog() != DialogResult.OK) return;
key = dialog.Key;
}
}
Application.Run(new MainForm());
}
}
What about editing the saved files?
Someone can change checked.txt to stretch the grace period. They gain days offline, not a license: a wrong key is still refused as soon as the server answers. If that matters for your product, choose a shorter grace period, or use a signed offline file, which can't be edited.
Storing the key in plain text is fine. It is the customer's own key, and the device limit is what stops it being shared.
What this does not stop
C# compiles to IL, and a decompiler turns IL back into readable code. A determined person can patch the check out of your build. Signed answers stop fake servers and key generators. For the rest, use an obfuscator, publish with Native AOT where your app allows it, and keep work that is worth stealing on a server.
Sell it
Connect Stripe, Paddle or Gumroad and each buyer is emailed a key. The customer portal lets them move to a new computer without writing to you.
Seats, usage credits, update checks and offline files are on the C# page.
Frequently asked questions
Where should a C# app store the license key?
In a file under LocalApplicationData, or in the user's registry hive. It does not need to be encrypted: the key belongs to that customer, and the server's device limit stops it being used everywhere.
Does this work with .NET Framework?
Yes. The Licers package targets .NET Standard 2.0, so it runs on .NET Framework 4.6.1 and later, .NET Core, .NET 5 and newer, Mono and Unity.
Should I check the license only at startup?
Startup is enough for most apps. For software that runs for days, check again every few hours and treat a network error the same way: as a reason to retry, not to lock the customer out.
Can I add license keys without my own server?
Yes. Use a hosted licensing service, or signed license files that your app verifies by itself. In both cases the private key that signs stays off the customer's computer.