public static Uri AddFragment(this Uri uri, string fragment)
{
if (uri == null)
{
throw new ArgumentNullException("uri");
}
if (uri.Scheme == "urn")
{
return AddName(uri, fragment);
}
if (fragment != null)
{
var iri = new StringBuilder(uri.ToString());
if (uri.Fragment.Length > 0)
{
int hash = iri.ToString().LastIndexOf('#');
iri.Remove(hash, 1);
if (iri[hash - 1] != '/')
{
iri.Insert(hash, '/');
}
}
else if ((iri[iri.Length - 1] != '/') && (uri.Query.Length == 0))
{
iri.Append('/');
}
iri.Append("#");
iri.Append(fragment);
return new Uri(iri.ToString());
}
return uri;
}