Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I resolve a relative path in both a web/Windows app in C#

I have an assembly that will be used in both a desktop app and an asp.net website.

I need to deal with relative paths (local files, not urls) in either situation.

How can I implement this method?

string ResolvePath(string path);

Under a web environment, I'd expect the method to behave like this (where d:\wwwroot\mywebsite is the folder IIS points at):

/folder/file.ext => d:\wwwroot\mywebsite\folder\file.ext
~/folder/file.ext => d:\wwwroot\mywebsite\folder\file.ext
d:\wwwroot\mywebsite\folder\file.ext => d:\wwwroot\mywebsite\folder\file.ext

For a desktop environment: (where c:\program files\myprogram\bin\ is the path of the .exe)

/folder/file.ext => c:\program files\myprogram\bin\folder\file.ext
c:\program files\myprogram\bin\folder\file.ext => c:\program files\myprogram\bin\folder\file.ext

I'd rather not inject a different IPathResolver depending on what state it's running in.

How do I detect which environment I'm in, and then what do I need to do in each case to resolve the possibly-relative path?

like image 835
Andrew Bullock Avatar asked Nov 18 '25 00:11

Andrew Bullock


1 Answers

I don't think the original question was answered.

Let assume you want "..\..\data\something.dat" relative to, lets say the executable in "D:\myApp\source\bin\". Using

System.IO.Path.Combine(Environment.CurrentDirectory, relativePath);

will simply return "D:\myApp\source\bin..\..\data\something.dat" which is also easily obtained by simply concatenating strings. Combine doesn't resolve paths, it handles trailing backslashes and other trivialities. He probably wants to run:

System.IO.Path.GetFullPath("D:\myApp\source\bin..\..\data\something.dat");

To get the a resolved path: "D:\myApp\data\something.dat".

like image 121
Lapsus Avatar answered Nov 19 '25 14:11

Lapsus