Get relative Path of a file C#
Asked Answered
V

3

12

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.

Vallejo answered 6/12, 2016 at 11:42 Comment(1)
This is an option as well: #3314640Ruffin
W
13

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".

Willyt answered 6/12, 2016 at 11:45 Comment(0)
K
2

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, e.g.

    var asm = Assembly.GetCallingAssembly();
    using (var stream = asm.GetManifestResourceStream(resource))
    {
        var reader = new StreamReader(stream);
        return reader.ReadToEnd();
    }
    
Kropotkin answered 6/12, 2016 at 12:19 Comment(0)
C
1

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).

Compte answered 6/12, 2016 at 12:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.