简体   繁体   中英

How to identify the path of a file in a solution in C#?

I am trying to access a data file (xml file) from a folder which is at a different hierarchical level from the caller test code. I created a relative path (../../testdata.xml) to make it understand to the test code and load the file. However, the same data file needs to be accessed by another piece of code which is not at the same hierarchical level as the test code. As a result, it is failing to load the file with FileNotFoundException which is as expected. Can someone please help me to define the path for the test data file so that it could be accessed by both callers residing at different hierarchical levels in the solution? Is there a way to identify the root path of the solution file and define the path of the test data file using solution file location as reference? Please help.

$(SolutionDir) The directory of the solution (defined as drive + path); includes the trailing backslash '\\'.

Macros for Build Commands and Properties: https://msdn.microsoft.com/en-us/library/c02as0cs.aspx

I suggest specify relative path of a file to base directory in the configuration file ( ex .. data/testdata.xml ).

Now you can resolve file location (from any file) using BaseDirectory property as shown.

var filepath = AppDomain.CurrentDomain.BaseDirectory + "data/testdata.xml";  // absolute path from config.

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