直接使用 `dotnet run app.cs` 运行 C# 文件。
Run a C# file directly using dotnet run app.cs

原始链接: https://devblogs.microsoft.com/dotnet/announcing-dotnet-run-app/

.NET 10 预览版 4 引入了一种更简单的运行 C# 代码的方式:`dotnet run app.cs`。这消除了快速脚本、实验和学习中对项目文件的需求,使 C# 更易于上手。这项名为基于文件应用的新功能,将单个 .cs 文件视为脚本,类似于 Python 或 JavaScript。 新的文件级指令,例如 `#:package`、`#:sdk` 和 `#:property`,允许你在 .cs 文件中指定 NuGet 包、SDK 和构建属性。Shebang 行(`#!`)支持跨平台的 C# shell 脚本。 当你的脚本规模扩大时,`dotnet project convert app.cs` 会将其转换为具有 .csproj 文件的标准项目,从而无缝地转换你的代码。 虽然社区已经存在一些无需项目的 C# 工具,但这种内置的支持提供了对完整 C# 语言的即时、无需设置的访问。预计在未来的 .NET 10 预览版中,VS Code 支持、调试和多文件处理将得到进一步改进。这项功能旨在使 C# 对新手更易于上手,对经验丰富的开发者更高效。

Hacker News 上正在讨论微软的新功能:直接使用 `dotnet run app.cs` 运行 C# 文件。虽然其简洁性受到称赞,但启动开销是一个令人担忧的问题,首次运行最多需要 2.5 秒,后续运行速度更快。一些用户报告说,不同的系统开销时间也不同,macOS 大约需要 1 秒,而其他系统则低至 63 毫秒。这与 Swift 等语言的近乎即时启动时间形成对比。 尽管目前性能存在问题,.NET 团队的开发人员已经承认了这个问题,并正在积极努力优化未来的版本。这项功能被视为在脚本场景中替代 PowerShell 的潜在方案,并降低了 C# 新手入门门槛。虽然有人将其与 LINQPad 和 CSX 等现有解决方案进行比较,但这项新功能旨在提高可访问性并简化工作流程。讨论还涉及依赖项管理、项目结构以及与 Python 和 Java 等其他语言的比较。评论指出它有可能增强 PowerShell,使编写粘合代码更容易。

原文

We are super excited to introduce a new feature that was released as part of .NET 10 Preview 4 that makes getting started with C# easier than ever. You can now run a C# file directly using dotnet run app.cs. This means you no longer need to create a project file or scaffold a whole application to run a quick script, test a snippet, or experiment with an idea. It’s simple, intuitive, and designed to streamline the C# development experience, especially for those just getting started.

What is dotnet run app.cs?

Until now, executing C# code using the dotnet CLI required a project structure that included a .csproj file. With this new capability, which we call file-based apps, you can run a standalone .cs file directly, much like you would with scripting languages such as Python or JavaScript.

This lowers the entry barrier to trying out C# and makes the language a much more attractive choice for learning, prototyping, or automation scenarios.

  • Quick Start, No Project File Required – Great for learning, experimentation, and small scripts.
  • First-Class CLI Integration – No extra tools, no dependencies, just dotnet and your .cs file.
  • Scales to Real Applications – This isn’t a separate dialect or runtime. When your script grows up, it can evolve into a full-fledged project using the same language, syntax, and tooling.

New file-level directives for file-based C# apps

With .NET 10 Preview 4, file-based apps also support a set of powerful file-level directives that allow to declare a small number of important things that are stored in project files for project-based apps, all without leaving your single .cs file. These directives make file-based apps more flexible and expressive while maintaining compatibility with MSBuild concepts.

Referencing NuGet packages with #:package

You can add NuGet package references directly in your .cs file using the #:package directive:

#:package [email protected]

using Humanizer;

var dotNet9Released = DateTimeOffset.Parse("2024-12-03");
var since = DateTimeOffset.Now - dotNet9Released;

Console.WriteLine($"It has been {since.Humanize()} since .NET 9 was released.");

Specifying an SDK with #:sdk

By default, file-based apps use the Microsoft.NET.Sdk SDK. If you’re building something like a web API, you can change the SDK using the #:sdk directive:

#:sdk Microsoft.NET.Sdk.Web

This tells the tooling to treat the file as if it were part of a web project, enabling features of ASP.NET Core like Minimal APIs and MVC.

Setting MSBuild properties with #:property

You can configure additional build properties using #:property. For example:

#:property LangVersion preview

This allows your file-based app to opt into advanced language features and platform targeting, without needing a full project file.

Using shebang lines for shell scripts

File-based apps also support shebang lines (#!), allowing you to write cross-platform C# shell scripts that are executable directly on Unix-like systems. For example:

#!/usr/bin/dotnet run
Console.WriteLine("Hello from a C# script!");

You can make the file executable and run it directly:

chmod +x app.cs
./app.cs

This makes C# a convenient option for CLI utilities, automation scripts, and tooling, no project setup required.

Converting to a project-based app

When your file-based app grows in complexity, or you simply want the extra capabilities afforded in project-based apps, you can convert it to a standard project with:

dotnet project convert app.cs

This command creates a new directory named for your file, scaffolds a .csproj file, moves your code into a Program.cs file, and translates any #: directives into MSBuild properties and references.

Example

Given this file:

#:sdk Microsoft.NET.Sdk.Web
#:package Microsoft.AspNetCore.OpenApi@10.*-*

var builder = WebApplication.CreateBuilder();

builder.AddOpenApi();

var app = builder.Build();

app.MapGet("/", () => "Hello, world!");
app.Run();

The generated .csproj would be:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.*-*" />
  </ItemGroup>

</Project>

This makes the transition seamless, from a single file to a fully functional, buildable, and extensible project.

Existing ways to run C# without projects

This is far from the first time developers have wanted to run C# without a project. Community projects like CS-Script, dotnet-script, Cake, and others have long filled this role, enabling scripting workflows, REPL experiences, and other experiences with C#. Here’s a blog post by Scott Hanselman from 2018 detailing the dotnet-script global tool.

These tools remain valuable and are worth checking out, especially for more advanced scripting scenarios. However, with this new built-in support, developers can get started immediately: no additional installation, configuration, or discovery steps required.

Equally important: this isn’t a separate dialect or mode of C#. We’re being intentional about making this feature a natural earlier “click-stop” from a regular C# project-based app. You’re writing the same C#, using the same compiler, and when your code grows up, it transitions naturally into a project-based app, if and when you want.

Getting Started

  1. Install .NET 10 Preview 4 Download and install it from dotnet.microsoft.com.
  2. Install Visual Studio Code (recommended) If you’re using Visual Studio Code, install the C# Dev Kit and then follow these instructions to update the C# extension for file-based apps support:

    To enable support for file-based apps and directives, you’ll need the latest pre-release version of the C# extension:

    • Open the Extensions sidebar (Ctrl+Shift+X)
    • Search for “C#”
    • In the extension page, click the Switch to Pre-Release Version button
    • Ensure the version installed is at least 2.79.8
  3. Write your code Create a file called hello.cs:
    Console.WriteLine("Hello, world!");
  4. Run it! Open a terminal in the same folder and run:
    dotnet run hello.cs
  5. Convert to a project To convert the file to a project, run:
    dotnet project convert hello.cs

Learn more

Watch this feature in action in this demo session from Microsoft Build: No projects, just C# with dotnet run app.cs

You’ll see how easy it is to get started, explore directives, and convert to a full project when ready.

You’ll see how easy it is to get started, explore directives, and convert to a full project when ready.

The road ahead

With dotnet run app.cs, we’re making C# more approachable, while preserving the full power and depth of the .NET ecosystem. Whether you’re prototyping, teaching, or building production systems, this new capability helps you move faster from idea to execution.

In upcoming .NET 10 previews we’re aiming to improve the experience of working with file-based apps in VS Code, with enhnanced IntelliSense for the new file-based directives, improved performance, and support for debugging. At the command line we’re exploring support for file-based apps with multiple files, and ways to make running file-based apps faster.

Try it out today and send your feedback to GitHub as we continue to shape this experience during .NET 10 and beyond.

联系我们 contact @ memedata.com