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.
path relative_path const; (since C++17) Returns path relative to root-path , that is, a pathname composed of every generic-format component of * this after root-path .
The problem is that relative filepath are relative to the current working directory and not relative to the .exe's path. You can easily test that. Open a command window, change to a directory that is not the path where the exe is and run the program by specifiying the full path to the .exe.
There are 2 main methods that can be used to generate the relative path of a file in C#, the Path class, and the resources.resx file.
relativeTo or path is null. relativeTo or path is effectively empty. Paths are resolved by calling the GetFullPath method before calculating the difference. The method uses the default file path comparison for the current platform ( StringComparison.OrdinalIgnoreCase for Windows and MacOs, StringComparison.Ordinal for Linux.
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.
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();
}
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With