如何在C#中正确获取Resources目录下JSON文件的路径
Hey there! Since you're transitioning from Java to C#, it's totally normal to run into path-related snags—let's get your JSON file loading correctly in no time.
Why Your Current Path Isn't Working
The problem here is that when you run your app in Visual Studio, the executable lives in the bin/Debug (or bin/Release) directory, so relative paths like ../MovieLibrary/Resources/movies-filtered.json don't resolve to your project's actual Resources folder. The runtime context shifts after compilation, so we need a more reliable way to target the file.
Solution 1: Copy the JSON File to the Output Directory (Recommended for Deployment)
This is the most straightforward approach for apps that will be deployed, as it ensures the JSON file travels with your compiled code:
- In Visual Studio, right-click your
movies-filtered.jsonfile in theResourcesfolder. - Select Properties from the menu.
- Set Copy to Output Directory to Copy if newer (or Copy always if you want to overwrite every build).
Now, you can build the path relative to your app's runtime directory. Update your LoadObjectsFromJsonFile method like this:
public void LoadObjectsFromJsonFile() { // Get the base directory where your app is running (bin/Debug/Release) string baseDirectory = AppDomain.CurrentDomain.BaseDirectory; // Combine the base path with the Resources folder and filename string filePath = Path.Combine(baseDirectory, "Resources", "movies-filtered.json"); using (StreamReader sr = new StreamReader(filePath)) { var jsonContent = sr.ReadToEnd(); Movies = JsonConvert.DeserializeObject<List<Movie>>(jsonContent); } }
Solution 2: Directly Target the Project's Resources Folder (Good for Debugging)
If you prefer to read the file directly from your project's Resources folder without copying it to the output, you can navigate up from the runtime directory to the project root:
public void LoadObjectsFromJsonFile() { // Navigate up three levels from bin/Debug to reach the project root string projectRoot = Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory)? .Parent? .Parent? .FullName; if (string.IsNullOrEmpty(projectRoot)) { throw new InvalidOperationException("Could not locate the project root directory."); } string filePath = Path.Combine(projectRoot, "Resources", "movies-filtered.json"); using (StreamReader sr = new StreamReader(filePath)) { var jsonContent = sr.ReadToEnd(); Movies = JsonConvert.DeserializeObject<List<Movie>>(jsonContent); } }
Quick Notes to Avoid Headaches
- Double-check the filename and folder structure: Typos or mismatched capitalization (while Windows is case-insensitive) can still cause issues.
- For Solution 1, always verify the file is in
bin/Debug/Resourcesafter building—if not, recheck the "Copy to Output Directory" setting. - If you're deploying the app, Solution 1 is the way to go, as it ensures the JSON file is included in the deployment package.
内容的提问来源于stack exchange,提问作者JeyKey

