Reputation: 37378
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?
Upvotes: 3
Views: 6170
Reputation: 469
The website binaries are copied to a temp folder when the application runs - so you usually can't get the relative path from the excecuting assembly.
This may not be a sensible way of doing this - but what I did to solve this problem was something like this:
if (filepath.StartsWith("~"))
{
filepath = HttpContext.Current.Server.MapPath(filepath);
}
else
{
filepath = System.IO.Path.Combine(Environment.CurrentDirectory, filepath);
}
This is because on the web version - a relative path has a ~ at the front - so I can tell if it's come from the web.config or the App.config.
Upvotes: 2
Reputation: 51
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".
Upvotes: 5
Reputation: 421968
As mentioned in John's comment, relative to what? You can use System.IO.Path.Combine
method to combine a base path with a relative path like:
System.IO.Path.Combine(Environment.CurrentDirectory, relativePath);
You can replace Environment.CurrentDirectory
in the above line with whatever base path you want.
You could store the base path in the configuration file.
Upvotes: 1