.NET Core 2控制台应用无法读取config.json数据求助
Hey, I’ve run into this exact issue a bunch of times with .NET configuration files—let’s walk through the most likely fixes for your problem:
1. Your config.json isn’t being copied to the output directory (most probable fix)
This is the #1 gotcha here. Your config.json lives in your project folder, but by default, Visual Studio doesn’t copy it to the directory where your compiled program runs (like bin/Debug/net6.0 or similar). Since you set optional: true in AddJsonFile(), the builder won’t throw an error—it’ll just load an empty configuration, which is why you’re getting null.
How to fix it:
- Right-click your
config.jsonfile in Visual Studio → Select Properties - In the Copy to Output Directory dropdown, choose Copy if newer or Copy always
- Recompile and run your program—your
beepvalue should load correctly now
2. The current working directory isn’t what you expect
Directory.GetCurrentDirectory() returns the directory your program is running from, which might not be your project folder or output directory depending on your debug settings or deployment environment. If the path doesn’t point to where config.json is, the builder can’t find it.
How to verify:
Add a quick line to print the current directory and check if it matches where your config.json is located:
var currentDir = Directory.GetCurrentDirectory(); Console.WriteLine($"Current working directory: {currentDir}");
If it’s wrong, you can either adjust your project’s debug working directory setting or specify an absolute path to config.json in AddJsonFile().
3. Double-check your JSON structure & syntax
While your sample config.json looks valid, it’s worth confirming:
- No typos or syntax errors (like missing commas, unclosed quotes, or mismatched braces)
- The
beepkey is at the root level of the JSON (not nested inside another object, like{"settings": {"beep": "bopp"}}—that would requireconfig.GetSection("settings:beep").Valueinstead)
Quick test to confirm the file is being loaded
Temporarily set optional: false in your AddJsonFile() call. This will make the builder throw a FileNotFoundException if it can’t find the file, which immediately tells you if the problem is a missing file vs. something else:
IConfigurationRoot config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("config.json", optional: false, reloadOnChange: true) .Build();
内容的提问来源于stack exchange,提问作者Konrad Viltersten




