Domanda

Qualcuno potrebbe dirmi come estrarre il nome del server da un UNC?

es.

// servername / directory / directory

Modifica : Mi scuso ma sembra che debba chiarire un errore: il percorso in realtà è più simile a:

// servername / d $ / directory

So che questo potrebbe cambiare un po 'le cose

È stato utile?

Soluzione

Che ne dici di Uri:

Uri uri = new Uri(@"\\servername\d$\directory");
string[] segs = uri.Segments;
string s = "http://" + uri.Host + "/" + 
    string.Join("/", segs, 2, segs.Length - 2) + "/";

Altri suggerimenti

Solo un'altra opzione, al fine di mostrare diverse opzioni:

(?<=^//)[^/]++


Il nome del server sarà in \0 o $0 o semplicemente il risultato della funzione, a seconda di come la chiami e di cosa offre la tua lingua.


Spiegazione in modalità commento regex:

(?x)      # flag to enable regex comments
(?<=      # begin positive lookbehind
^         # start of line
//        # literal forwardslashes (may need escaping as \/\/ in some languages)
)         # end positive lookbehind
[^/]++    # match any non-/ and keep matching possessively until a / or end of string found.
          # not sure .NET supports the possessive quantifier (++) - a greedy (+) is good enough here.

Questo dovrebbe fare il trucco.

^//([^/]+).*

Il nome del server si trova nel primo gruppo di acquisizione

Espressione regolare da abbinare a servername:

^//(\w+)

Brutto ma funziona semplicemente:

var host = uncPath.Split(new [] {'\\'}, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top