从 IHttpHandler(通用处理程序)中的文件路径获取 URL
在我的 IHttpHandler 类(对于 .ashx 页面)中,我想在目录中搜索某些文件,并返回相对 url。我可以获取文件,没问题:
string dirPath = context.Server.MapPath("~/mydirectory");
string[] files = Directory.GetFiles(dirPath, "*foo*.txt");
IEnumerable<string> relativeUrls = files.Select(f => WHAT GOES HERE? );
What is theiest way to conversion file paths torelative urls?如果我在 aspx 页面中,我可以说 this.ResolveUrl()
。我知道我可以进行一些字符串解析和字符串替换来获取相对 URL,但是是否有一些内置方法可以为我处理所有这些问题?
编辑:为了澄清,在不进行自己的字符串解析的情况下,我如何从 this:
"E:\Webs\WebApp1\WebRoot\mydirectory\foo.txt"
转到 this:
"/mydirectory/foo.txt"
我正在寻找一个现有的方法,例如:
public string GetRelativeUrl(string filePath) { }
In my IHttpHandler class (for an .ashx page), I want to search a directory for certain files, and return relative urls. I can get the files, no problem:
string dirPath = context.Server.MapPath("~/mydirectory");
string[] files = Directory.GetFiles(dirPath, "*foo*.txt");
IEnumerable<string> relativeUrls = files.Select(f => WHAT GOES HERE? );
What is the easiest way to convert file paths to relative urls? If I were in an aspx page, I could say this.ResolveUrl()
. I know I could do some string parsing and string replacement to get the relative url, but is there some built-in method that will take care of all of that for me?
Edit: To clarify, without doing my own string parsing, how do I go from this:
"E:\Webs\WebApp1\WebRoot\mydirectory\foo.txt"
to this:
"/mydirectory/foo.txt"
I'm looking for an existing method like:
public string GetRelativeUrl(string filePath) { }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试 System.Web.Hosting.HostingEnvironment.MapPath 方法,它是静态的,可以在 Web 应用程序中的任何位置访问。
try
System.Web.Hosting.HostingEnvironment.MapPath
method, its static and can be accessed everywhere in web application.我可以想象很多人都有这个问题...我的解决方案是:
更新
或从文件名到虚拟路径(尚未测试过;您可能还需要一些类似于上面 ResoveRelative 的代码。 ..让我知道它是否有效):
I can imagine a lot of people having this question... My solution is:
update
Or from filename to virtual path (haven't tested it; you might need some code similar to ResoveRelative above as well... let me know if it works):