简体   繁体   中英

ASP.NET Core read content files while debugging

I have some json files that I need to read from my asp.net core app. They are under a folder called data

--MyProject
---Startup.cs
---Data
------dataset1.json
------dataset2.json

I am using IHostingEnvironment ContentRootPath to read the files:

 string pathToFile = hostingEnvironment.ContentRootPath
                            + Path.DirectorySeparatorChar
                            + "Data"
                            + Path.DirectorySeparatorChar
                            + "dataset1.json"

which returns C:\\SourceControl\\Test.Backend\\src\\Test.Web\\Data\\dataset1.json

This works fine when I publish my code in IIS. However when I am debugging the files are copied into bin folder and the above code does not work. How can I read the files while debugging?

#if DEBUG

 string pathToFile = hostingEnvironment.ContentRootPath
                        + Path.DirectorySeparatorChar
                        + "bin"
                        + Path.DirectorySeparatorChar
                        + "Data"
                        + Path.DirectorySeparatorChar
                        + "dataset1.json"

#else

string pathToFile = hostingEnvironment.ContentRootPath
                        + Path.DirectorySeparatorChar
                        + "Data"
                        + Path.DirectorySeparatorChar
                        + "dataset1.json"

#endif

you can have two different paths when you are in debug mode and in production with this approach. Just change the first path to your needs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM