Skip to main content

Fixed: "error CS9297: '#:' directives cannot be after first token in file"

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

#:property and #:package lines configure a one-file C# program, so they have to come before anything else in it. Mine was below a using, so the build stopped with CS9297. Moving it up fixes it.

What I Was Doing​

I was adding #:property PublishAot=false to a one-file C# program, to stop an error from System.Text.Json. I put it just under the using line:

app.cs
using System.Text.Json;
#:property PublishAot=false

Console.WriteLine(JsonSerializer.Serialize(new { Id = 1, Name = "Cable" }));
Terminal
dotnet run app.cs

What I Expected​

One line of JSON.

What I Got​

Output
/Users/you/projects/hello/app.cs(2,2): error CS9297: '#:' directives cannot be after first token in file

The build failed. Fix the build errors and run again.

dotnet run app.cs printing error CS9297: '#:' directives cannot be after first token in file, at line 2, and The build failed.

What I Checked​

Which line it meant. app.cs(2,2) is line 2, column 2: the #:property line.

What counts as a token. using is the first token in this file. Comments and blank lines aren't tokens.

The documentation. Microsoft's file-based apps page says of #:include, #:package, #:project, #:property and #:sdk: "Place these directives at the top of the C# file."

Why It Happens​

These lines aren't C# code. They tell the SDK how to build the file, so it has to read them before it deals with the code. A using is code.

The Fix​

Move every #: line above the first using:

app.cs
#:property PublishAot=false

using System.Text.Json;

Console.WriteLine(JsonSerializer.Serialize(new { Id = 1, Name = "Cable" }));

After the Fix​

Terminal
dotnet run app.cs
Output
{"Id":1,"Name":"Cable"}

With the directive on the first line, dotnet run app.cs printing the JSON with Id 1 and Name Cable.

Common Mistakes​

MistakeWhat happensDo this instead
Grouping #:package with its usingCS9297Put all the #: lines first
Adding one at the end of a file, as you notice you need itCS9297Move it up

Troubleshooting​

SymptomLikely causeFix
CS9297 on a line near the topSomething above it is codeCheck for a using or a statement
dotnet run app.cs treats it as a projectA .csproj in the same folder can change what it doesKeep the file in its own folder

Conclusion​

Every #: line goes above the first line of code, including using lines.

Additional Resources​

Stay Updated

Subscribe to our newsletter for the latest tutorials, tech insights, and developer news.

By subscribing, you agree to our privacy policy. Unsubscribe at any time.