Introduction
Developers regularly create small utilities to solve everyday problems. These tools might read log files, convert JSON data, check API responses, rename files, compare configuration values, or generate reports. Most of these tasks do not require a complete application architecture, multiple projects, or a large solution structure.
However, creating even a small C# utility traditionally involves setting up a project, managing package references, configuring the build, and maintaining additional files. This setup is reasonable for applications that will grow over time, but it can feel unnecessary for a tool that performs one focused task.
.NET file-based applications provide a simpler alternative. They allow developers to build and run C# programs directly from a single source file without creating a traditional .csproj file. The .NET 11 SDK continues this approach and adds capabilities such as including additional source files and managing project references directly from the command line.
In this article, we will explore how file-based applications work, create a practical log analysis tool, manage dependencies, pass command-line arguments, and understand when this approach is suitable for developer utilities.
What Are File-Based Apps in .NET?
A file-based application is a C# program that can be built and executed directly from a .cs file. Instead of requiring a project file, the .NET SDK generates the necessary build configuration automatically.
For example, a traditional console application usually contains files similar to these:
LogAnalyzer/
LogAnalyzer.csproj
Program.cs
appsettings.jsonA file-based application can start with just:
LogAnalyzer.csYou can execute it directly using:
dotnet run --file LogAnalyzer.csThe SDK handles the build and dependency restoration required to run the application.
File-based apps are useful for:
Small command-line utilities.
Developer automation scripts.
Testing an API or library.
Data conversion tools.
Learning and experimenting with C#.
One-time maintenance tasks.
Small internal tools that do not need a complex project structure.
They are still regular C# programs. You can use classes, interfaces, records, asynchronous methods, collections, and other language features. The main difference is how the application is configured and launched.
Creating Your First File-Based App
Start by installing the .NET 11 SDK. Then create a file named HelloTool.cs.
Add the following code:
Console.WriteLine("Hello from a .NET file-based app!");
Console.WriteLine(
$"Running on .NET {Environment.Version}");Open a terminal in the directory containing the file and execute:
dotnet run --file HelloTool.csThe SDK builds and runs the application without requiring a separate project file.
You can also use the shorter syntax:
dotnet run HelloTool.csHowever, using --file makes your intention explicit, particularly when working in a directory that also contains a traditional project.
You can pass arguments to the application by placing them after the double-dash separator:
dotnet run --file HelloTool.cs -- first secondThe application can access these values through the args collection.
Understanding File-Based App Directives
One of the useful features of file-based applications is the ability to define build settings and dependencies directly inside the C# source file.
These settings use directives that begin with #:.
The main directives include:
Directive | Purpose |
|---|---|
#:package | Adds a NuGet package reference |
#:project | References another .NET project |
#:include | Includes additional source or supported files |
#:property | Sets an MSBuild property |
#:sdk | Selects the SDK used to build the application |
For example, you can add a package reference directly to your source file:
#:package [email protected]
using Spectre.Console;
AnsiConsole.MarkupLine(
"[green]Application started successfully.[/]");The package directive removes the need to edit a project file just to add a dependency.
When specifying a package version, use an explicit version or the supported latest-version syntax. Omitting the version normally requires central package management to be configured.
These directives should appear at the beginning of the source file, before normal C# code.
Building a Practical Log Analysis Tool
Let's create a small utility that reads an application log file and reports how many entries belong to different log levels.
For example, an application may produce logs like these:
2026-11-25 09:10:12 INFO Application started
2026-11-25 09:11:18 WARN Database response was slow
2026-11-25 09:12:25 ERROR Database connection failed
2026-11-25 09:13:40 INFO Retry started
2026-11-25 09:14:02 ERROR Request processing failedInstead of opening the file and counting entries manually, we can build a small C# utility that performs the analysis.
Create a file named LogAnalyzer.cs and add the following implementation:
using System.Text.RegularExpressions;
if (args.Length == 0)
{
Console.WriteLine(
"Usage: dotnet run --file LogAnalyzer.cs -- <log-file>");
return;
}
string filePath = args[0];
if (!File.Exists(filePath))
{
Console.WriteLine("Log file not found.");
return;
}
var counts = new Dictionary<string, int>(
StringComparer.OrdinalIgnoreCase)
{
["INFO"] = 0,
["WARN"] = 0,
["ERROR"] = 0,
["DEBUG"] = 0
};
var pattern = new Regex(
@"\b(INFO|WARN|ERROR|DEBUG)\b",
RegexOptions.IgnoreCase);
int totalLines = 0;
int unmatchedLines = 0;
using var reader = new StreamReader(filePath);
while (reader.ReadLine() is string line)
{
totalLines++;
var match = pattern.Match(line);
if (!match.Success)
{
unmatchedLines++;
continue;
}
string level = match.Value.ToUpperInvariant();
counts[level]++;
}
Console.WriteLine();
Console.WriteLine("Log Analysis Report");
Console.WriteLine("-------------------");
foreach (var item in counts)
{
Console.WriteLine(
$"{item.Key,-8}: {item.Value}");
}
Console.WriteLine("-------------------");
Console.WriteLine($"Total lines: {totalLines}");
Console.WriteLine($"Unmatched lines: {unmatchedLines}");This application accepts the log file path as a command-line argument. It checks whether the file exists before starting the analysis.
The StreamReader reads the file one line at a time. This is a useful approach when working with large log files because the application does not need to load the entire file into memory.
A regular expression identifies the log level in each line. The dictionary maintains the count for each supported level.
Finally, the application prints a summary report.
Run the tool with:
dotnet run --file LogAnalyzer.cs -- application.logThe output will look similar to:
Log Analysis Report
-------------------
INFO : 2
WARN : 1
ERROR : 2
DEBUG : 0
-------------------
Total lines: 5
Unmatched lines: 0This is a simple example, but the same approach can be extended to calculate error percentages, identify frequent exceptions, group logs by date, or generate CSV reports.
Using NuGet Packages Without a Project File
Small utilities often need external libraries. For example, a developer may want to use a package for JSON processing, command-line interfaces, or HTTP communication.
File-based apps support NuGet dependencies through the #:package directive.
Consider a utility that needs to work with JSON data using Newtonsoft.Json.
Add the package reference:
#:package [email protected]
using Newtonsoft.Json.Linq;
string json = """
{
"application": "LogAnalyzer",
"environment": "Development",
"enabled": true
}
""";
var data = JObject.Parse(json);
Console.WriteLine(
$"Application: {data["application"]}");
Console.WriteLine(
$"Environment: {data["environment"]}");When the application runs, the SDK restores the package and makes it available to the source file.
This is useful when experimenting with a library or creating a small utility that needs only one or two external dependencies.
For a larger application with many dependencies and different configuration requirements, a traditional project file provides more centralized control.
Including Additional Files in .NET 11
A file-based application starts with one source file, but that does not mean every line of code must remain in the same file forever.
.NET 11 supports the #:include directive, which allows an application to include additional source files and supported content files.
For example, consider this folder structure:
LogTool/
LogAnalyzer.cs
LogHelpers.csThe main file can include the helper file:
#:include LogHelpers.cs
Console.WriteLine(
LogHelpers.GetApplicationName());The LogHelpers.cs file can contain:
public static class LogHelpers
{
public static string GetApplicationName()
{
return "LogAnalyzer";
}
}The included C# file contributes declarations to the application. It should not contain another set of top-level statements.
This feature is particularly useful when a small utility begins to grow. You can move reusable logic into separate files without immediately converting the application into a traditional project.
The include directive also supports patterns for including multiple files. However, using glob patterns currently disables file-based app build caching, so explicit paths may be preferable when predictable incremental builds matter.
Referencing an Existing .NET Project
Sometimes a small utility needs to use an existing class library rather than duplicating its logic.
.NET 11 adds support for managing project references through the dotnet reference command.
For example:
dotnet reference add --file LogAnalyzer.cs ../SharedLibrary/SharedLibrary.csprojThis adds a project reference to the file-based application.
You can list the references using:
dotnet reference list --file LogAnalyzer.csAnd remove a reference using:
dotnet reference remove --file LogAnalyzer.cs ../SharedLibrary/SharedLibrary.csprojThis makes it easier to reuse existing application components while keeping the utility itself lightweight.
It is especially helpful when a development team already has shared libraries for logging, authentication, data access, or common business rules.
Publishing and Running File-Based Apps
File-based applications support more than development-time execution. You can also build and publish them using the .NET CLI.
For example:
dotnet build LogAnalyzer.csTo publish:
dotnet publish LogAnalyzer.cs -c ReleaseFile-based apps enable Native AOT publishing by default. Native AOT can produce a self-contained executable without requiring the .NET runtime to be installed separately on the target machine.
However, Native AOT has platform and library compatibility requirements. Some libraries use reflection or dynamic code generation in ways that require additional configuration or are not supported.
If you do not need Native AOT, you can disable it in the source file:
#:property PublishAot=falseThis is useful when a tool depends on libraries that are not ready for Native AOT or when you want a simpler managed deployment.
Always test the published output on the target environment rather than assuming that a successful development run guarantees a successful deployment.
File-Based Apps vs Traditional .NET Projects
Both approaches use the .NET SDK and C# language features, but they serve different development needs.
Area | File-based app | Traditional project |
|---|---|---|
Initial setup | Minimal | Requires project setup |
Project file | Not required | Required |
Dependencies | Source-file directives | Project file |
Source organization | Single file with optional includes | Multiple files and folders |
Project references | Supported through directives and CLI | Supported through project configuration |
Build configuration | Simplified | More control |
Best use case | Small utilities and experiments | Larger applications and libraries |
Team development | Suitable for focused tools | Better for structured solutions |
A file-based app is not a replacement for every .NET project. It is another option for situations where a small program does not need the additional structure of a traditional project.
Best Practices for Small Developer Tools
Keep the tool focused
A small utility should solve one clearly defined problem. Avoid adding unnecessary layers, abstractions, or configuration systems when a few methods can handle the task.
Validate command-line arguments
Check required arguments before accessing files, databases, or external services. Provide useful usage instructions so that another developer can understand how to run the tool.
Use streams for large files
Prefer StreamReader, FileStream, and asynchronous stream APIs when processing large files. Avoid loading complete files into memory unless their size is known to be small.
Keep dependencies limited
A file-based app makes package references easy to add. However, every additional dependency increases restore, build, and maintenance requirements. Use packages only when they provide clear value.
Store configuration outside the source code
Use command-line arguments or environment variables for file paths, endpoints, and environment-specific settings. Avoid hardcoding values that change between machines.
Use source control
A single source file is still application code. Store important utilities in source control, document their purpose, and review changes like any other developer tool.
Convert to a project when necessary
When the utility needs multiple developers, automated tests, complex configuration, reusable libraries, or a larger deployment process, consider converting it into a traditional .NET project.
Common Mistakes to Avoid
One common mistake is assuming that a file-based app does not need dependency management. Package references still require compatible versions and successful NuGet restoration.
Another mistake is placing the source file in a directory containing an unrelated project and using ambiguous run commands. Using --file explicitly avoids confusion about which application the CLI should execute.
Developers may also assume that adding more files automatically makes a file-based app a traditional project. Included files remain part of the file-based workflow and follow its supported rules.
Finally, do not assume that Native AOT supports every NuGet package. Review compatibility warnings and test the published executable before distributing it.
Advantages and Disadvantages
Advantages
Reduces the setup required for small C# utilities.
Allows direct execution without creating a project file.
Supports NuGet packages through source-file directives.
Supports additional files and project references in .NET 11.
Works with familiar .NET CLI commands.
Provides a convenient way to experiment with libraries and APIs.
Supports publishing, including Native AOT deployment.
Disadvantages
A single-file structure can become difficult to maintain as the application grows.
Complex build customization is easier to manage in a traditional project.
Native AOT compatibility may require additional work.
Team conventions and IDE workflows may favor project-based applications.
Build behavior can be affected by configuration files in parent directories.
Some advanced application structures are better represented through traditional projects.
Summary
.NET 11 file-based applications provide a practical way to create small C# developer tools without starting with a traditional project structure. Developers can run a source file directly, add NuGet dependencies, accept command-line arguments, and use familiar .NET APIs.
The newer file inclusion and project reference capabilities make the approach more flexible when a utility starts to grow. You can separate helper code and reuse existing libraries while keeping the entry point lightweight.
For log analysis, file conversion, API checks, automation, and other focused tasks, file-based apps reduce unnecessary setup and help developers move quickly from an idea to a working utility.
The important decision is knowing when to keep the application small and when to move to a traditional project. Use file-based apps for focused tools and experiments, and choose a structured project when the application needs more extensive organization, testing, and long-term maintenance.


Join the conversation! Your thoughts help the community grow.