C# Path.Combine 用于 URL 吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/372865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Path.Combine for URLs?
提问by Brian MacKay
Path.Combineis handy, but is there a similar function in the .NET framework for URLs?
Path.Combine很方便,但是 .NET 框架中是否有类似的URL 功能?
I'm looking for syntax like this:
我正在寻找这样的语法:
Url.Combine("http://MyUrl.com/", "/Images/Image.jpg")
which would return:
这将返回:
"http://MyUrl.com/Images/Image.jpg"
"http://MyUrl.com/Images/Image.jpg"
采纳答案by Michael Freidgeim
There is a Todd Menier's comment abovethat Flurlincludes a Url.Combine
.
上面有Todd Menier 的评论,Flurl包含一个Url.Combine
.
More details:
更多细节:
Url.Combine is basically a Path.Combine for URLs, ensuring one and only one separator character between parts:
Url.Combine 基本上是一个用于 URL 的 Path.Combine,确保各部分之间只有一个分隔符:
var url = Url.Combine(
"http://MyUrl.com/",
"/too/", "/many/", "/slashes/",
"too", "few?",
"x=1", "y=2"
// result: "http://www.MyUrl.com/too/many/slashes/too/few?x=1&y=2"
Get Flurl.Http on NuGet:
PM> Install-Package Flurl.Http
PM> 安装包 Flurl.Http
Or get the stand-alone URL builderwithout the HTTP features:
或者获取没有 HTTP 功能的独立 URL 构建器:
PM> Install-Package Flurl
PM> 安装包 Flurl
回答by Ryan Cook
You use Uri.TryCreate( ... )
:
你使用Uri.TryCreate( ... )
:
Uri result = null;
if (Uri.TryCreate(new Uri("http://msdn.microsoft.com/en-us/library/"), "/en-us/library/system.uri.trycreate.aspx", out result))
{
Console.WriteLine(result);
}
Will return:
将返回:
http://msdn.microsoft.com/en-us/library/system.uri.trycreate.aspx
http://msdn.microsoft.com/en-us/library/system.uri.trycreate.aspx
回答by mtazva
Witty example, Ryan, to end with a link to the function. Well done.
机智的例子,瑞安,以该函数的链接结束。做得好。
One recommendation Brian: if you wrap this code in a function, you may want to use a UriBuilder to wrap the base URL prior to the TryCreate call.
一个建议 Brian:如果您将此代码包装在一个函数中,您可能希望在 TryCreate 调用之前使用 UriBuilder 来包装基本 URL。
Otherwise, the base URL MUST include the scheme (where the UriBuilder will assume http://). Just a thought:
否则,基本 URL 必须包含方案(其中 UriBuilder 将假定为 http://)。只是一个想法:
public string CombineUrl(string baseUrl, string relativeUrl) {
UriBuilder baseUri = new UriBuilder(baseUrl);
Uri newUri;
if (Uri.TryCreate(baseUri.Uri, relativeUrl, out newUri))
return newUri.ToString();
else
throw new ArgumentException("Unable to combine specified url values");
}
回答by Matthew Sharpe
This may be a suitably simple solution:
这可能是一个适当简单的解决方案:
public static string Combine(string uri1, string uri2)
{
uri1 = uri1.TrimEnd('/');
uri2 = uri2.TrimStart('/');
return string.Format("{0}/{1}", uri1, uri2);
}
回答by Joel Beckham
Uri
has a constructor that should do this for you: new Uri(Uri baseUri, string relativeUri)
Uri
有一个构造函数可以为您执行此操作: new Uri(Uri baseUri, string relativeUri)
Here's an example:
下面是一个例子:
Uri baseUri = new Uri("http://www.contoso.com");
Uri myUri = new Uri(baseUri, "catalog/shownew.htm");
Note from editor: Beware, this method does not work as expected. It can cut part of baseUri in some cases. See comments and other answers.
编辑注意:请注意,此方法无法按预期工作。在某些情况下,它可以削减部分 baseUri。查看评论和其他答案。
回答by Jeronimo Colon III
Based on the sample URLyou provided, I'm going to assume you want to combine URLs that are relative to your site.
根据您提供的示例URL,我将假设您想要组合与您的站点相关的 URL。
Based on this assumption I'll propose this solution as the most appropriate response to your question which was: "Path.Combine is handy, is there a similar functionin the framework for URLs?"
基于这个假设,我将提出这个解决方案作为对您的问题的最合适的回答:“Path.Combine 很方便,URL 框架中是否有类似的功能?”
Since there the is a similar functionin the framework for URLs I propose the correct is: "VirtualPathUtility.Combine" method. Here's the MSDN reference link: VirtualPathUtility.Combine Method
由于URL 框架中有类似的功能,我建议正确的是:“VirtualPathUtility.Combine”方法。这是 MSDN 参考链接:VirtualPathUtility.Combine Method
There is one caveat: I believe this only works for URLs relative to your site (that is, you cannot use it to generate links to another web site. For example, var url = VirtualPathUtility.Combine("www.google.com", "accounts/widgets");
).
有一个警告:我相信这仅适用于相对于您网站的 URL(也就是说,您不能使用它来生成指向另一个网站的链接。例如,var url = VirtualPathUtility.Combine("www.google.com", "accounts/widgets");
)。
回答by Brian MacKay
Ryan Cook's answer is close to what I'm after and may be more appropriate for other developers. However, it adds http:// to the beginning of the string and in general it does a bit more formatting than I'm after.
Ryan Cook 的回答接近我所追求的,可能更适合其他开发人员。但是,它将 http:// 添加到字符串的开头,并且通常它比我所追求的格式要多一些。
Also, for my use cases, resolving relative paths is not important.
此外,对于我的用例,解析相对路径并不重要。
mdsharp's answer also contains the seed of a good idea, although that actual implementation needed a few more details to be complete. This is an attempt to flesh it out (and I'm using this in production):
mdsharp 的回答还包含一个好主意的种子,尽管实际实现需要更多细节才能完成。这是一种充实它的尝试(我正在生产中使用它):
C#
C#
public string UrlCombine(string url1, string url2)
{
if (url1.Length == 0) {
return url2;
}
if (url2.Length == 0) {
return url1;
}
url1 = url1.TrimEnd('/', '\');
url2 = url2.TrimStart('/', '\');
return string.Format("{0}/{1}", url1, url2);
}
VB.NET
网络
Public Function UrlCombine(ByVal url1 As String, ByVal url2 As String) As String
If url1.Length = 0 Then
Return url2
End If
If url2.Length = 0 Then
Return url1
End If
url1 = url1.TrimEnd("/"c, "\"c)
url2 = url2.TrimStart("/"c, "\"c)
Return String.Format("{0}/{1}", url1, url2)
End Function
This code passes the following test, which happens to be in VB:
这段代码通过了以下测试,恰好是在 VB 中:
<TestMethod()> Public Sub UrlCombineTest()
Dim target As StringHelpers = New StringHelpers()
Assert.IsTrue(target.UrlCombine("test1", "test2") = "test1/test2")
Assert.IsTrue(target.UrlCombine("test1/", "test2") = "test1/test2")
Assert.IsTrue(target.UrlCombine("test1", "/test2") = "test1/test2")
Assert.IsTrue(target.UrlCombine("test1/", "/test2") = "test1/test2")
Assert.IsTrue(target.UrlCombine("/test1/", "/test2/") = "/test1/test2/")
Assert.IsTrue(target.UrlCombine("", "/test2/") = "/test2/")
Assert.IsTrue(target.UrlCombine("/test1/", "") = "/test1/")
End Sub
回答by Alex
An easy way to combine them and ensure it's always correct is:
组合它们并确保它始终正确的一种简单方法是:
string.Format("{0}/{1}", Url1.Trim('/'), Url2);
回答by Chris Marisic
I have to point out that Path.Combine
appears to work for this also directly, at least on .NET 4.
我必须指出,这Path.Combine
似乎也直接适用于这一点,至少在 .NET 4 上。
回答by urza
I just put together a small extension method:
我只是整理了一个小的扩展方法:
public static string UriCombine (this string val, string append)
{
if (String.IsNullOrEmpty(val)) return append;
if (String.IsNullOrEmpty(append)) return val;
return val.TrimEnd('/') + "/" + append.TrimStart('/');
}
It can be used like this:
它可以像这样使用:
"www.example.com/".UriCombine("/images").UriCombine("first.jpeg");
回答by JeremyWeir
Path.Combine("Http://MyUrl.com/", "/Images/Image.jpg").Replace("\", "/")