/ Align = "left" / Połącz adresy URL?

/ align = "left" / Łączenie jest przydatne, ale czy istnieje podobna funkcja w. NET framework dla adresów URL ?

Szukam składni takiej jak ta:

Url.Combine("http://MyUrl.com/", "/Images/Image.jpg")

Który zwróci:

"http://MyUrl.com/Images/Image.jpg"

Author: Peter Mortensen, 2008-12-17

30 answers

Uri posiada konstruktor, który powinien to zrobić za ciebie: new Uri(Uri baseUri, string relativeUri)

Oto przykład:

Uri baseUri = new Uri("http://www.contoso.com");
Uri myUri = new Uri(baseUri, "catalog/shownew.htm");
 1021
Author: Joel Beckham,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-20 08:52:35

Używasz 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);
}

Powróci:

Http://msdn.microsoft.com/en-us/library/system.uri.trycreate.aspx

 131
Author: Ryan Cook,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-12-16 21:49:56

Może to być odpowiednio proste rozwiązanie:

public static string Combine(string uri1, string uri2)
{
    uri1 = uri1.TrimEnd('/');
    uri2 = uri2.TrimStart('/');
    return string.Format("{0}/{1}", uri1, uri2);
}
 126
Author: Matt Sharpe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-09-25 10:29:57

Jest już kilka świetnych odpowiedzi tutaj. W oparciu o sugestię mdsharpe, oto metoda rozszerzenia, która może być łatwo używana, gdy chcesz radzić sobie z instancjami Uri:

using System;
using System.Linq;

public static class UriExtensions
{
    public static Uri Append(this Uri uri, params string[] paths)
    {
        return new Uri(paths.Aggregate(uri.AbsoluteUri, (current, path) => string.Format("{0}/{1}", current.TrimEnd('/'), path.TrimStart('/'))));
    }
}

I przykład użycia:

var url = new Uri("http://example.com/subpath/").Append("/part1/", "part2").AbsoluteUri;

To da http://example.com/subpath/part1/part2

 106
Author: Ales Potocnik Hahonina,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-20 05:17:34

To pytanie ma kilka świetnych, wysoko głosowanych odpowiedzi!

Odpowiedź Ryana Cooka jest zbliżona do tego, czego szukam i może być bardziej odpowiednia dla innych programistów. Jednak dodaje http:// na początku łańcucha i ogólnie robi trochę więcej formatowania niż jestem po.

Również, w moich przypadkach użycia, rozwiązywanie ścieżek względnych nie jest ważne.

Odpowiedź Mdsharp zawiera również zalążek dobrego pomysłu, chociaż rzeczywiste wdrożenie wymagało kilku szczegółów, aby być kompletna. To jest próba zgładzenia go (i używam tego w produkcji):

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

Ten kod przechodzi następujący test, który zdarza się być w 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
 80
Author: Brian MacKay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-07 19:22:44

Na podstawie przykładowego adresu URL , który podałeś, zakładam, że chcesz połączyć adresy URL, które są względne do twojej witryny.

W oparciu o to założenie zaproponuję To rozwiązanie jako najbardziej odpowiednią odpowiedź na twoje pytanie, które brzmiało: "ścieżka.Kombajn jest poręczny, czy istnieje podobna funkcja w ramach adresów URL?"

Ponieważ istnieje podobna funkcja w ramach adresów URL proponuję poprawne: "VirtualPathUtility.Combine" metoda. Oto link referencyjny MSDN: VirtualPathUtility.Metoda Łączenia

Jest jedno zastrzeżenie: wierzę, że działa to tylko dla adresów URL w stosunku do witryny (to znaczy, nie można go użyć do generowania linków do innej witryny sieci web. Na przykład var url = VirtualPathUtility.Combine("www.google.com", "accounts/widgets");).

 32
Author: Jeronimo Colon III,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-20 09:05:29

Ścieżka.Combine nie działa dla mnie, ponieważ w argumentach QueryString mogą znajdować się znaki typu"|", a tym samym Url, co spowoduje wywołanie argumentu.

Po raz pierwszy wypróbowałem nowe podejście Uri (Uri baseUri, string relativeUri), które nie powiodło się dla mnie, ponieważ Uri jest podobne http://www.mediawiki.org/wiki/Special:SpecialPages:

new Uri(new Uri("http://www.mediawiki.org/wiki/"), "Special:SpecialPages")

Spowoduje Special: SpecialPages, ponieważ dwukropek po Special oznacza schemat.

Więc w końcu musiałem wybrać trasę mdsharpe / Brian MacKays i opracować ją nieco dalej do pracy z wieloma częściami uri:

public static string CombineUri(params string[] uriParts)
{
    string uri = string.Empty;
    if (uriParts != null && uriParts.Count() > 0)
    {
        char[] trims = new char[] { '\\', '/' };
        uri = (uriParts[0] ?? string.Empty).TrimEnd(trims);
        for (int i = 1; i < uriParts.Count(); i++)
        {
            uri = string.Format("{0}/{1}", uri.TrimEnd(trims), (uriParts[i] ?? string.Empty).TrimStart(trims));
        }
    }
    return uri;
}

Użycie: CombineUri("http://www.mediawiki.org/", "wiki", "Special:SpecialPages")

 28
Author: Mike Fuchs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-19 11:12:16
Path.Combine("Http://MyUrl.com/", "/Images/Image.jpg").Replace("\\", "/")
 22
Author: JeremyWeir,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-01-11 21:41:18

I just put together 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('/');
        }

Może być użyty w następujący sposób:

"www.example.com/".UriCombine("/images").UriCombine("first.jpeg");
 14
Author: urza,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-11-25 08:43:19

Dowcipny przykład, Ryan, aby zakończyć linkiem do funkcji. Dobra robota.

Jedna rekomendacja Brian: jeśli zawijasz ten kod w funkcję, możesz użyć Uribuildera do zawinięcia podstawowego adresu URL przed wywołaniem TryCreate.

W przeciwnym razie, bazowy adres URL musi zawierać schemat (gdzie UriBuilder przyjmie http://). Tylko myśl:

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");
}
 11
Author: mtazva,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-03 15:04:45

Łączenie wielu części adresu Url może być trochę trudne. Możesz użyć konstruktora 2 parametrów Uri(baseUri, relativeUri), lub możesz użyć funkcji użytkowej Uri.TryCreate(). W obu przypadkach możesz zwrócić nieprawidłowy wynik, Ponieważ Metody te nadal obcinają względne części pierwszego parametru baseUri, tzn. z czegoś w rodzaju http://google.com/some/thing do http://google.com

Aby móc połączyć wiele części w ostateczny adres url, możesz skopiować 2 poniższe funkcje:

    public static string Combine(params string[] parts)
    {
        if (parts == null || parts.Length == 0) return string.Empty;

        var urlBuilder = new StringBuilder();
        foreach (var part in parts)
        {
            var tempUrl = tryCreateRelativeOrAbsolute(part);
            urlBuilder.Append(tempUrl);
        }
        return VirtualPathUtility.RemoveTrailingSlash(urlBuilder.ToString());
    }

    private static string tryCreateRelativeOrAbsolute(string s)
    {
        System.Uri uri;
        System.Uri.TryCreate(s, UriKind.RelativeOrAbsolute, out uri);
        string tempUrl = VirtualPathUtility.AppendTrailingSlash(uri.ToString());
        return tempUrl;
    }

Pełny kod z testami jednostkowymi aby zademonstrować użycie można znaleźć na https://uricombine.codeplex.com/SourceControl/latest#UriCombine/Uri.cs

Mam testy jednostkowe, aby objąć 3 najczęstsze przypadki: Tutaj wpisz opis obrazka

 8
Author: Believe2014,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-24 13:43:22

Ta odpowiedź prawdopodobnie zagubi się we wszystkich powyższych odpowiedziach, ale znalazłem UriBuilder działa naprawdę dobrze na tego typu rzeczy.

UriBuilder urlb = new UriBuilder("http", _serverAddress, _webPort, _filePath);
Uri url = urlb.Uri;
return url.AbsoluteUri;

Zobacz Klasa UriBuilder - MSDN Po Więcej konstruktorów i dokumentacji.

 7
Author: javajavajavajavajava,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-20 11:41:06

Wiem, że to zostało rozwiązane, ale łatwym sposobem, aby je połączyć i upewnić się, że zawsze jest poprawna jest..

string.Format("{0}/{1}", Url1.Trim('/'), Url2);
 6
Author: Alex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-05-12 21:42:32

Oto metoda Microsoft (OfficeDev PnP) Urlutyczność.Połączyć :

    const char PATH_DELIMITER = '/';

    /// <summary>
    /// Combines a path and a relative path.
    /// </summary>
    /// <param name="path"></param>
    /// <param name="relative"></param>
    /// <returns></returns>
    public static string Combine(string path, string relative) 
    {
        if(relative == null)
            relative = String.Empty;

        if(path == null)
            path = String.Empty;

        if(relative.Length == 0 && path.Length == 0)
            return String.Empty;

        if(relative.Length == 0)
            return path;

        if(path.Length == 0)
            return relative;

        path = path.Replace('\\', PATH_DELIMITER);
        relative = relative.Replace('\\', PATH_DELIMITER);

        return path.TrimEnd(PATH_DELIMITER) + PATH_DELIMITER + relative.TrimStart(PATH_DELIMITER);
    }

Source: GitHub

 4
Author: Chris Marisic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-06 21:25:44

Moje ogólne rozwiązanie:

public static string Combine(params string[] uriParts)
{
    string uri = string.Empty;
    if (uriParts != null && uriParts.Any())
    {
        char[] trims = new char[] { '\\', '/' };
        uri = (uriParts[0] ?? string.Empty).TrimEnd(trims);

        for (int i = 1; i < uriParts.Length; i++)
        {
            uri = string.Format("{0}/{1}", uri.TrimEnd(trims), (uriParts[i] ?? string.Empty).TrimStart(trims));
        }
    }

    return uri;
}
 3
Author: Alex Titarenko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-17 07:52:20

Wiem, że jestem spóźniony na imprezę, ale stworzyłem tę funkcję, która ułatwi Ci życie.]}

    /// <summary>
    /// the ultimate Path combiner of all time
    /// </summary>
    /// <param name="IsURL">
    /// true - if the paths are internet urls,false - if the paths are local urls,this is very important as this will be used to decide which separator will be used
    /// </param>
    /// <param name="IsRelative">just adds the separator at the beginning</param>
    /// <param name="IsFixInternal">fix the paths from within (by removing duplicate separators and correcting the separators)</param>
    /// <param name="parts">the paths to combine</param>
    /// <returns>the combined path</returns>
    public static string PathCombine(bool IsURL , bool IsRelative , bool IsFixInternal , params string[] parts)
    {
        if (parts == null || parts.Length == 0) return string.Empty;
        char separator = IsURL ? '/' : '\\';

        if (parts.Length == 1 && IsFixInternal)
        {

            string validsingle;
            if (IsURL)
            {
                validsingle = parts[0].Replace('\\' , '/');
            }
            else
            {
                validsingle = parts[0].Replace('/' , '\\');
            }
            validsingle = validsingle.Trim(separator);
            return (IsRelative ? separator.ToString() : string.Empty) + validsingle;
        }

        string final = parts
            .Aggregate
            (
            (string first , string second) =>
            {
                string validfirst;
                string validsecond;
                if (IsURL)
                {
                    validfirst = first.Replace('\\' , '/');
                    validsecond = second.Replace('\\' , '/');
                }
                else
                {
                    validfirst = first.Replace('/' , '\\');
                    validsecond = second.Replace('/' , '\\');
                }
                var prefix = string.Empty;
                if (IsFixInternal)
                {
                    if (IsURL)
                    {
                        if (validfirst.Contains("://"))
                        {
                            var tofix = validfirst.Substring(validfirst.IndexOf("://") + 3);
                            prefix = validfirst.Replace(tofix , string.Empty).TrimStart(separator);

                            var tofixlist = tofix.Split(new[] { separator } , StringSplitOptions.RemoveEmptyEntries);

                            validfirst = separator + string.Join(separator.ToString() , tofixlist);
                        }
                        else
                        {
                            var firstlist = validfirst.Split(new[] { separator } , StringSplitOptions.RemoveEmptyEntries);
                            validfirst = string.Join(separator.ToString() , firstlist);
                        }

                        var secondlist = validsecond.Split(new[] { separator } , StringSplitOptions.RemoveEmptyEntries);
                        validsecond = string.Join(separator.ToString() , secondlist);
                    }
                    else
                    {
                        var firstlist = validfirst.Split(new[] { separator } , StringSplitOptions.RemoveEmptyEntries);
                        var secondlist = validsecond.Split(new[] { separator } , StringSplitOptions.RemoveEmptyEntries);

                        validfirst = string.Join(separator.ToString() , firstlist);
                        validsecond = string.Join(separator.ToString() , secondlist);
                    }

                }
                return prefix + validfirst.Trim(separator) + separator + validsecond.Trim(separator);
            }
            );
        return (IsRelative ? separator.ToString() : string.Empty) + final;
    }

Działa zarówno dla adresów URL, jak i zwykłych ścieżek

Użycie:

    //fixes internal paths
    Console.WriteLine(PathCombine(true , true , true , @"\/\/folder 1\/\/\/\\/\folder2\///folder3\\/" , @"/\somefile.ext\/\//\"));
    //result : /folder 1/folder2/folder3/somefile.ext


    //doesn't fix internal paths
    Console.WriteLine(PathCombine(true , true , false , @"\/\/folder 1\/\/\/\\/\folder2\///folder3\\/" , @"/\somefile.ext\/\//\"));
    //result : /folder 1//////////folder2////folder3/somefile.ext


    //don't worry about url prefixes when fixing internal paths
    Console.WriteLine(PathCombine(true , false , true , @"/\/\/https:/\/\/\lul.com\/\/\/\\/\folder2\///folder3\\/" , @"/\somefile.ext\/\//\"));
    //result : https://lul.com/folder2/folder3/somefile.ext


    Console.WriteLine(PathCombine(false , true , true , @"../../../\\..\...\./../somepath" , @"anotherpath"));
    //result : \..\..\..\..\...\.\..\somepath\anotherpath
 3
Author: bigworld12,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-21 18:19:05

Wiem, że to pytanie jest dobrze odpowiedział, jednak uważam, że to przydatne, ponieważ ma następujące cechy

  • rzuca na null lub białą spację
  • Klasa statyczna, która ściślej naśladuje System.Io.Path
  • pobiera params parametr dla wielu segmentów Url

Uwaga: adres URL nazwy klasy może zostać zmieniony, ponieważ istnieje klasa systemowaSystem.Security.Policy.Url

Klasa

public static class Url
{
   private static string InternalCombine(string source, string dest)
   {

      // If the source is null or white space retune the dest only
      if (string.IsNullOrWhiteSpace(source))
      {
         throw new ArgumentException("Cannot be null or white space", "source");
         // throw new ArgumentException("Cannot be null or white space", nameof(source)); // c# 6.0 Nameof Expression
      }

      if (string.IsNullOrWhiteSpace(dest))
      {
         throw new ArgumentException("Cannot be null or white space", "dest");
         // throw new ArgumentException("Cannot be null or white space", nameof(dest)); // c# 6.0 Nameof Expression
      }

      source =  source.TrimEnd('/', '\\');
      dest = dest.TrimStart('/', '\\');

      return string.Format("{0}/{1}", source, dest);
      // return $"{source}/{dest}"; // c# 6.0 string interpolation
   }

   public static string Combine(string source, params string[] args)
   {
      return args.Aggregate(source, InternalCombine);
   }
}

Wyniki

Url.Combine("test1", "test2");    
Url.Combine("test1//", "test2"); 
Url.Combine("test1", "/test2");

// Result = test1/test2

Url.Combine(@"test1\/\/\/", @"\/\/\\\\\//test2", @"\/\/\\\\\//test3\") ;

// Result = test1/test2/test3

Url.Combine("/test1/", "/test2/", null);
Url.Combine("", "/test2/");
Url.Combine("/test1/", null);

// Throws an ArgumentException
 2
Author: TheGeneral,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-28 02:16:46

There is a a comment above that Flurl include a Url.Połącz.

Więcej Szczegółów:

Url.Połączenie jest w zasadzie ścieżką.Połącz dla adresów URL, zapewniając jeden i tylko jeden znak separatora między częściami:

var url = Url.Combine(
    "http://foo.com/",
    "/too/", "/many/", "/slashes/",
    "too", "few?",
    "x=1", "y=2"
// result: "http://www.foo.com/too/many/slashes/too/few?x=1&y=2" 
 2
Author: Michael Freidgeim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-13 06:00:13

Co ty na to?

 public static class WebPath
    {
        public static string Combine(params string[] args)
        {
            var prefixAdjusted = args.Select(x => x.StartsWith("/") && !x.StartsWith("http") ? x.Substring(1) : x);
            return string.Join("/", prefixAdjusted);
        }
    }
 1
Author: Martin Murphy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-10 15:31:30

Oto moje podejście i wykorzystam je również dla siebie

public static string UrlCombine(string part1, string part2)
{
    string newPart1 = string.Empty;
    string newPart2 = string.Empty;
    string seprator = "/";

    // if either part1 or part 2 is empty,
    // we don't need to combine with seprator
    if (string.IsNullOrEmpty(part1) || string.IsNullOrEmpty(part2))
    {
        seprator = string.Empty;
    }

    // if part1 is not empty
    // remove '/' at last
    if (!string.IsNullOrEmpty(part1))
    {
        newPart1 = part1.TrimEnd('/');
    }

    // if part2 is not empty
    // remove '/' at first
    if (!string.IsNullOrEmpty(part2))
    {
        newPart2 = part2.TrimStart('/');
    }

    // now finally combine
    return string.Format("{0}{1}{2}", newPart1, seprator, newPart2);
}
 1
Author: Amit Bhagat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-03 03:39:54
    private Uri UriCombine(string path1, string path2, string path3 = "", string path4 = "")
    {
        string path = System.IO.Path.Combine(path1, path2.TrimStart('\\', '/'), path3.TrimStart('\\', '/'), path4.TrimStart('\\', '/'));
        string url = path.Replace('\\','/');
        return new Uri(url);
    }

Ma zalety zachowania się dokładnie tak jak Path.Combine

 1
Author: TruthOf42,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-18 15:31:39

Reguły podczas łączenia adresów URL z URI

Aby uniknąć dziwnych zachowań należy przestrzegać jednej zasady:

  • path (katalog) musi kończyć się znakiem'/'. jeśli ścieżka kończy się bez'/', ostatnia część jest traktowana jak nazwa pliku i będzie konkatenowana podczas próby połączenia z następną częścią url.
  • Istnieje 1 wyjątek: podstawowy adres URL (bez informacji o katalogu) nie musi kończyć się na ' / '
  • część ścieżki nie może zaczynać się od'/', jeśli zaczyna się od '/' każdego istniejącego względnego informacje z adresu URL są usuwane...dodawanie ciągu.Pusta ścieżka części usunie również katalog względny z adresu URL!

Jeśli zastosujesz się do powyższych zasad, możesz połączyć adresy URL z poniższym kodem. w zależności od sytuacji, możesz dodać wiele części "katalogu" do adresu url...

        var pathParts = new string[] { destinationBaseUrl, destinationFolderUrl, fileName };

        var destination = pathParts.Aggregate((left, right) =>
        {
            if (string.IsNullOrWhiteSpace(right))
                return left;

            return new Uri(new Uri(left), right).ToString();
        });
 1
Author: baHI,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-05 05:04:15

Dlaczego po prostu nie użyć następujących.

System.IO.Path.Combine(rootUrl, subPath).Replace(@"\", "/")
 1
Author: Andreas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-17 13:11:56

Więcej sugestii... Połączyłem wszystkie powyższe:

    public static string UrlPathCombine(string path1, string path2)
    {
        path1 = path1.TrimEnd('/') + "/";
        path2 = path2.TrimStart('/');

        return Path.Combine(path1, path2)
            .Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
    }

    [TestMethod]
    public void TestUrl()
    {
        const string P1 = "http://msdn.microsoft.com/slash/library//";
        Assert.AreEqual("http://msdn.microsoft.com/slash/library/site.aspx", UrlPathCombine(P1, "//site.aspx"));

        var path = UrlPathCombine("Http://MyUrl.com/", "Images/Image.jpg");

        Assert.AreEqual(
            "Http://MyUrl.com/Images/Image.jpg",
            path);
    }
 0
Author: Per G,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-25 10:51:01

Cóż, po prostu łączę dwa ciągi znaków i używam wyrażeń regularnych do czyszczenia części.

    public class UriTool
    {
        public static Uri Join(string path1, string path2)
        {
            string url = path1 + "/" + path2;
            url = Regex.Replace(url, "(?<!http:)/{2,}", "/");

            return new Uri(url);
        }
    }

Więc możesz użyć TAK:

    string path1 = "http://someaddress.com/something/";
    string path2 = "/another/address.html";
    Uri joinedUri = UriTool.Join(path1, path2);

    // joinedUri.ToString() returns "http://someaddress.com/something/another/address.html"

Mam nadzieję, że może się komuś przydać!

 0
Author: Marcio Martins,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-21 18:44:13

Użyłem tego kodu do rozwiązania problemu:

string[] brokenBaseUrl = Context.Url.TrimEnd('/').Split('/');
string[] brokenRootFolderPath = RootFolderPath.Split('/');

for (int x = 0; x < brokenRootFolderPath.Length; x++)
{
    //if url doesn't already contain member, append it to the end of the string with / in front
    if (!brokenBaseUrl.Contains(brokenRootFolderPath[x]))
    {
        if (x == 0)
        {
            RootLocationUrl = Context.Url.TrimEnd('/');
        }
        else
        {
            RootLocationUrl += String.Format("/{0}", brokenRootFolderPath[x]);
        }
    }
}
 0
Author: Joshua Smith,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-17 15:50:50

Obie te prace

  Uri final = new Uri(Regex.Replace(baseUrl + "/" + relativePath, "(?<!http:)/{2,}", "/"));

Lub

  Uri final =new Uri(string.Format("{0}/{1}", baseUrl.ToString().TrimEnd('/'), relativePath.ToString().TrimStart('/')));

Ie

If

BaseUrl = " http://tesrurl.test.com/Int18 "

I

RelativePath = "To_folder"

Output = http://tesrurl.test.com/Int18/To_Folder

Niektóre błędy pojawią się w kodzie poniżej

 // if you use below code, some issues will be there in final uri
 Uri final= new Uri(baseUrl ,relativePath );
 0
Author: DAre G,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-24 07:43:08

Prosta jedna linijka:

public static string Combine(this string uri1, string uri2) => $"{uri1.TrimEnd('/')}/{uri2.TrimStart('/')}";

Zainspirowany odpowiedzią @ Matt Sharpe.

 0
Author: Nick N.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-06 12:41:07

Używamy prostej metody pomocniczej, aby połączyć dowolną liczbę części URL razem:

public static string JoinUrlParts(params string[] urlParts)
{
    return string.Join("/", urlParts.Where(up => !string.IsNullOrEmpty(up)).ToList().Select(up => up.Trim('/')).ToArray());
}

Uwaga, że nie obsługuje"../../ something / pageHTM ' - style relative URL-s!

 0
Author: pholpar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-22 14:19:05

Znalazłem, że Uri constructor przerzuca ' \ 'na'/'. Możesz więc również użyć ścieżki.Połącz, z Uri ctr.

 Uri baseUri = new Uri("http://MyUrl.com");
 string path = Path.Combine("Images","Image.jpg");
 Uri myUri = new Uri(baseUri , path);
 0
Author: skippy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-30 10:43:22