我有一个将在桌面应用程序和 asp.net 网站中使用的组件。
在这两种情况下,我都需要处理相对路径(本地文件,而不是 url)。
如何实现这个方法?
string ResolvePath(string path);
在 Web 环境下,id 期望该方法的行为如下(其中 d:\wwwroot\mywebsite
是 iis 指向的文件夹):
/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
对于桌面环境:(其中 c:\program files\myprogram\bin\
是 .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
我不想根据其运行状态注入(inject)不同的 IPathResolver
。
我如何检测我所处的环境,然后在每种情况下我需要做什么来解析可能的相对路径?
谢谢
最佳答案
我认为原始问题没有得到解答。
假设您想要“..\..\data\something.dat”相对于“D:\myApp\source\bin\”中的可执行文件。使用
System.IO.Path.Combine(Environment.CurrentDirectory, relativePath);
将简单地返回“D:\myApp\source\bin..\..\data\something.dat”,这也可以通过简单地连接字符串轻松获得。 Combine 不解析路径,它处理尾随的反斜杠和其他琐碎的事情。他可能想跑:
System.IO.Path.GetFullPath("D:\myApp\source\bin..\..\data\something.dat");
获取解析路径:“D:\myApp\data\something.dat”。
关于c# - 我如何在 C# 中解决 Web/Windows 应用程序中的相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1028195/