gpt4 book ai didi

c# - 从 IHttpHandler(通用处理程序)中的文件路径获取 URL

转载 作者:行者123 更新时间:2023-11-30 18:05:09 26 4
gpt4 key购买 nike

在我的 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? );

将文件路径转换为相对 URL 的最简单方法是什么?如果我在 aspx 页面中,我可以说 this.ResolveUrl()。我知道我可以进行一些字符串解析和字符串替换来获取相对 URL,但是是否有一些内置方法可以为我处理所有这些事情?

编辑:澄清一下,在不进行我自己的字符串解析的情况下,我该如何进行:

"E:\Webs\WebApp1\WebRoot\mydirectory\foo.txt"

为此:

"/mydirectory/foo.txt"

我正在寻找一个现有的方法,例如:

public string GetRelativeUrl(string filePath) { }

最佳答案

我可以想象很多人都有这个问题......我的解决方案是:

public static string ResolveRelative(string url)
{
var requestUrl = context.Request.Url;
string baseUrl = string.Format("{0}://{1}{2}{3}",
requestUrl.Scheme, requestUrl.Host,
(requestUrl.IsDefaultPort ? "" : ":" + requestUrl.Port),
context.Request.ApplicationPath);

if (toresolve.StartsWith("~"))
{
return baseUrl + toresolve.Substring(1);
}
else
{
return new Uri(new Uri(baseUrl), toresolve).ToString();
}
}

更新

或者从文件名到虚拟路径(还没有测试过;您可能还需要一些类似于上面的 ResoveRelative 的代码……如果可行请告诉我):

public static string GetUrl(string filename)
{
if (filename.StartsWith(context.Request.PhysicalApplicationPath))
{
return context.Request.ApplicationPath +
filename.Substring(context.Request.PhysicalApplicationPath.Length);
}
else
{
throw new ArgumentException("Incorrect physical path");
}
}

关于c# - 从 IHttpHandler(通用处理程序)中的文件路径获取 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5845358/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com