简体   繁体   中英

Get relative Path of a file C#

I currently writing a project in visual studio in c#. the project full path is:

"C:\TFS\MySolution\"

I have a file that I need to load during the execution. lets say the file path is

"C:\TFS\MySolution\Project1\NeedtoLoad.xml"

I don't want to write the full path hard coded, and want to get the path in a dynamic way.

I use the following line:

    var path = Directory.GetCurrentDirectory();

The problem that every method that I found and the above code line gets me the following path:

"C:\TFS\MySolution\Project1\bin\Debug"

And what I need is

"C:\TFS\MySolution\Project1\"

so I could concatenate

NeedtoLoad.xml

to the answer.

of course I could do:

path.Substring(0, path.IndexOf("bin\\Debug"));

But it is not that elegant.

You can use Directory.GetParent and its Parent member

string path = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;

Will go two levels up the path tree and return "C:\\TFS\\MySolution\\Project1" .

If the xml is a static part of you project (you don't override it during runtime) than probably the best thing is to include it into your dll.

  • Go to file Properties and make it Embedded Resource
  • Simply load it from dll resources, eg

    var asm = Assembly.GetCallingAssembly(); using (var stream = asm.GetManifestResourceStream(resource)) { var reader = new StreamReader(stream); return reader.ReadToEnd(); }

If that file is part of your project, you should make sure it's copied to your project output when you build.

Choose the file in solution explorer, and go to the properties pane in Visual Studio (F4). Select 'Content' as the 'Build action'. Now, when you build your solution, the file will be copied to the output directory (bin/Debug or bin/Release).

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