Domanda

Dato un assoluto URI / URL, voglio ottenere un URI / URL che non contiene la parte di foglia. Per esempio: http://foo.com/bar/baz.html , dovrei ottenere http://foo.com/bar/ .

Il codice che ho potuto venire con sembra un po 'lungo, quindi mi chiedo se c'è un modo migliore.

static string GetParentUriString(Uri uri)
    {            
        StringBuilder parentName = new StringBuilder();

        // Append the scheme: http, ftp etc.
        parentName.Append(uri.Scheme);            

        // Appned the '://' after the http, ftp etc.
        parentName.Append("://");

        // Append the host name www.foo.com
        parentName.Append(uri.Host);

        // Append each segment except the last one. The last one is the
        // leaf and we will ignore it.
        for (int i = 0; i < uri.Segments.Length - 1; i++)
        {
            parentName.Append(uri.Segments[i]);
        }
        return parentName.ToString();
    }

Si potrebbe utilizzare la funzione di qualcosa di simile a questo:

  static void Main(string[] args)
    {            
        Uri uri = new Uri("http://foo.com/bar/baz.html");
        // Should return http://foo.com/bar/
        string parentName = GetParentUriString(uri);                        
    }

Grazie, Rohit

È stato utile?

Soluzione

Questo è il più breve che posso venire con:

static string GetParentUriString(Uri uri)
{
    return uri.AbsoluteUri.Remove(uri.AbsoluteUri.Length - uri.Segments.Last().Length);
}

Se si desidera utilizzare il metodo Last (), si dovrà includere System.Linq.

Altri suggerimenti

Hai provato questo? Sembra abbastanza semplice.

Uri parent = new Uri(uri, "..");

Ci deve essere un modo più semplice per fare questo con il costruito in metodi uri ma qui è la mia torsione su @unknown (yahoo) 's suggerimento.
In questa versione non è necessario System.Linq e gestisce anche gli URI con le stringhe di query:

private static string GetParentUriString(Uri uri)
{
    return uri.AbsoluteUri.Remove(uri.AbsoluteUri.Length - uri.Segments[uri.Segments.Length -1].Length - uri.Query.Length);
}

rapido e sporco

int pos = uriString.LastIndexOf('/');
if (pos > 0) { uriString = uriString.Substring(0, pos); } 

via più breve che ho trovato:

static Uri GetParent(Uri uri) {
    return new Uri(uri, Path.GetDirectoryName(uri.LocalPath) + "/");
}

Ho letto molte risposte qui, ma non ho trovato uno che mi è piaciuto perché si rompono in alcuni casi.

Quindi, io sto usando questo:

public Uri GetParentUri(Uri uri) {
    var withoutQuery = new Uri(uri.GetComponents(UriComponents.Scheme |
                                                 UriComponents.UserInfo |
                                                 UriComponents.Host |
                                                 UriComponents.Port |
                                                 UriComponents.Path, UriFormat.UriEscaped));
    var trimmed = new Uri(withoutQuery.AbsoluteUri.TrimEnd('/'));
    var result = new Uri(trimmed, ".");
    return result;
}

Nota. Rimuove la query e il frammento intenzionalmente

new Uri(uri.AbsoluteUri + "/../")

Get segmenation of url

url="http://localhost:9572/School/Common/Admin/Default.aspx"

Dim name() As String = HttpContext.Current.Request.Url.Segments

now simply using for loop or by index, get parent directory name

code = name(2).Remove(name(2).IndexOf("/"))

This returns me, "Common"

PapyRef's answer is incorrect, UriPartial.Path includes the filename.

new Uri(uri, ".").ToString()

seems to be cleanest/simplest implementation of the function requested.

Thought I'd chime in; despite it being almost 10 years, with the advent of the cloud, getting the parent Uri is a fairly common (and IMO more valuable) scenario, so combining some of the answers here you would simply use (extended) Uri semantics:

public static Uri Parent(this Uri uri)
{
    return new Uri(uri.AbsoluteUri.Remove(uri.AbsoluteUri.Length - uri.Segments.Last().Length - uri.Query.Length).TrimEnd('/'));
}

var source = new Uri("https://foo.azure.com/bar/source/baz.html?q=1");

var parent = source.Parent();         // https://foo.azure.com/bar/source
var folder = parent.Segments.Last();  // source

I can't say I've tested every scenario, so caution advised.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top