public URL(string abs_parent, string rel_url) { parent = ParseAbs(abs_parent); if (rel_url.StartsWith("/")) { string real_url = parent.scheme + "://" + parent.host + rel_url; url_main = ParseAbs(real_url); url_main.org_str = real_url; return; } RelURL tmp_url = ParseRel(rel_url); int back_rest = BackProcess(ref tmp_url.path); parent = ParseAbs(abs_parent, back_rest); string result_path = ""; if (Regex.IsMatch(parent.path, "/$") && Regex.IsMatch(tmp_url.path, "^/")) { result_path = parent.path.Remove(0, parent.path.Length - 1) + tmp_url.path; } else if (Regex.IsMatch(parent.path, "[^/]$") && Regex.IsMatch(tmp_url.path, "^[^/]")) { result_path = parent.path + "/" + tmp_url.path; } else { result_path = parent.path + tmp_url.path; } string result = parent.scheme + "://" + parent.host + result_path + tmp_url.file + tmp_url.nav + tmp_url.query; url_main = ParseAbs(result); url_main.org_str = result; }
RelURL ParseRel(string url) { RelURL comp = new RelURL(); Match match = Regex.Match(url, rgx_rel); if (!match.Success) { throw new Exception("URL invalida"); } comp.path = ""; if (match.Groups["file"].Value == "..") { comp.path = ".."; comp.file = null; } else if (match.Groups["file"].Value != "") { comp.file = match.Groups["file"].Value;; } if (match.Groups["path"].Value != "") { comp.path = match.Groups["path"].Value + comp.path; } if (match.Groups["goto"].Value != "") { comp.nav = match.Groups["goto"].Value;; } if (match.Groups["query"].Value != "") { comp.query = match.Groups["query"].Value;; } return(comp); }
public RelURL RelativeTo(string absolute) { AbsURL parent = (new URL(absolute)).url_main; MatchCollection origin = Regex.Matches(parent.path, rgx_path); MatchCollection destiny = Regex.Matches(url_main.path, rgx_path); bool fill = false; string result = ""; //detecta diferentes hosts if (url_main.host != parent.host) { for (int pth = 0; pth < origin.Count; pth++) { result += "../"; } result += url_main.host; if (url_main.path == null && url_main.path == "") { result += "/"; } fill = true; } for (int c = 0; c < destiny.Count; c++) { //se rellena con los que quedan en destino if (fill) { result += destiny[c].Value; //origen es menor //--->se completa con los que resten } else if (origin.Count - 1 < c) { result += destiny[c].Value; //diferentes //---> a partir de aqui se completa con ../ por las que resten } else if (origin[c].Value != destiny[c].Value) { fill = true; for (int rest = 0; rest < origin.Count - c; rest++) { result += "../"; } result += destiny[c].Value; } //origen mayor que destino //--->completar con ../ if (c == destiny.Count - 1 && !fill && (origin.Count - 1) - c > 0) { for (int rest = 0; rest < (origin.Count - c) - 1; rest++) { result += "../"; } } } RelURL rel_url = new RelURL() { org_str = result + url_main.file + url_main.nav + url_main.query, path = result, file = url_main.file, nav = url_main.nav, query = url_main.query }; return(rel_url); }