我正在构建自定义面包屑,我希望每个 LinkButton 都有唯一的 commandArgument url。
我有一个通用字符串变量,它是一个 url。每个子站点的名称可以不同,只要层次不限即可。
String 变量可能如下所示:
http://site/org/content/Change/Book/process/item
我想做的是拆分字符串变量并将其添加到数组中,如下所示:
http://site/org
http://site/org/content/
http://site/org/content/Change/
http://site/org/content/Change/Book/
http://site/org/content/Change/Book/process/
http://site/org/content/Change/Book/process/item
我试过以下代码:
private void AddBreadCrumb(SPWeb web)
{
var webUrl = web.Url;
var linkList = new List<string>(webUrl.Split('/'));
// etc..
}
但它并不像我希望的那样。
任何形式的帮助都是适用的
最佳答案
您可以为此使用扩展方法和一些 LINQ
:
public static IEnumerable<string> ParseUrl(this string source)
{
if(!Uri.IsWellFormedUriString(source, UriKind.Absolute))
throw new ArgumentException("The URI Format is invalid");
var index = source.IndexOf("//");
var indices = source.Select((x, idx) => new {x, idx})
.Where(p => p.x == '/' && p.idx > index + 1)
.Select(p => p.idx);
// Skip the first index because we don't want http://site
foreach (var idx in indices.Skip(1))
{
yield return source.Substring(0,idx);
}
yield return source;
}
用法如下:
string url = "http://site/org/content/Change/Book/process/item";
var parts = url.ParseUrl();
LINQPad
中的结果:
关于c# - 如何剪切包含 url 的字符串并将其添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22631482/