How can I resolve relative path in web / windows application in C #

I have an assmebly that will be used both in the desktop application and on the asp.net website.

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

How can I implement this method?

string ResolvePath(string path);

Under the web envronment id, it expects the method to behave as follows (where d:\wwwroot\mywebsiteis the iis point of the folder in):

/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 the desktop environment: (where c:\program files\myprogram\bin\is the path to 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 would prefer not to enter another one IPathResolverdepending on the state in which it is working.

How do I determine which environment I enter and what I need to do in each case to resolve the possible path?

thanks

+3
3

, .

, ".. \..\data\something.dat" , , "D:\myApp\source\bin \".

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

"D:\myApp\source\bin.. \..\data\something.dat", , . , . , :

System.IO.Path.GetFullPath( "D:\MyApp\\Bin.. \..\Data\something.dat" );

: "D:\myApp\data\something.dat".

+5

- , excecuting.

, , , :

if (filepath.StartsWith("~"))
{
   filepath = HttpContext.Current.Server.MapPath(filepath);
}
else
{
  filepath = System.IO.Path.Combine(Environment.CurrentDirectory, filepath);
}

, - - ~ , , web.config App.config.

+2

, ? System.IO.Path.Combine , :

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

Environment.CurrentDirectory .

.

+1

Source: https://habr.com/ru/post/1711010/


All Articles