如何使用这些部分在C#中可靠地构建URL? [英] How to reliably build a URL in C# using the parts?

查看:75
本文介绍了如何使用这些部分在C#中可靠地构建URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直感觉自己在重新发明轮子,所以我想问一下这里的人群。想象一下,我有一个这样的代码片段:

  string protocol = http; //假设此值是从配置文件
string host = www.google.com;中检索到的; //假设此值是从配置文件
中获取的string path = plans / worlddomination.html; //假设此值是从配置文件

中检索的,我想构建url http://www.google.com/plans/worlddomination.html 。我一直通过编写如下俗气的代码来做到这一点:

  protocol = protocol.EndsWith(://)吗?协议:协议+://; 
path = path.StartsWith( /)吗? path: / +路径;
string fullUrl = string.Format( {0} {1} {2},协议,主机,路径);

我真正想要的是某种API,例如:

  UrlBuilder builder = new UrlBuilder(); 
builder.Protocol =协议;
builder.Host =主机;
builder.Path =路径;
builder.QueryString = null;
string fullUrl = builder.ToString();

我必须相信这在.NET框架中存在,但我从未遇到过。 / p>

构建万无一失(即永不格式错误)网址的最佳方法是什么?

解决方案

查看 UriBuilder类

b $ b

I keep feeling like I'm reinventing the wheel, so I thought I'd ask the crowd here. Imagine I have a code snippet like this:

string protocol = "http"; // Pretend this value is retrieved from a config file
string host = "www.google.com"; // Pretend this value is retrieved from a config file
string path = "plans/worlddomination.html"; // Pretend this value is retrieved from a config file

I want to build the url "http://www.google.com/plans/worlddomination.html". I keep doing this by writing cheesy code like this:

protocol = protocol.EndsWith("://") ? protocol : protocol + "://";
path = path.StartsWith("/") ? path : "/" + path;    
string fullUrl = string.Format("{0}{1}{2}", protocol, host, path);

What I really want is some sort of API like:

UrlBuilder builder = new UrlBuilder();
builder.Protocol = protocol;
builder.Host = host;
builder.Path = path;
builder.QueryString = null;
string fullUrl = builder.ToString();

I gotta believe this exists in the .NET framework somewhere, but nowhere I've come across.

What's the best way to build foolproof (i.e. never malformed) urls?

解决方案

Check out the UriBuilder class

这篇关于如何使用这些部分在C#中可靠地构建URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆