15

Would anyone be able to tell me how to pull the server name out of a UNC?

ex.

//servername/directory/directory

Edit : I apologize but it looks like I need to clarify a mistake: the path actually is more like:

//servername/d$/directory

I know this might change things a little

KevinDeus
  • 11,988
  • 20
  • 65
  • 97

6 Answers6

24

How about Uri:

Uri uri = new Uri(@"\\servername\d$\directory");
string[] segs = uri.Segments;
string s = "http://" + uri.Host + "/" + 
    string.Join("/", segs, 2, segs.Length - 2) + "/";
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
7

Just another option, for the sake of showing different options:

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


The server name will be in \0 or $0 or simply the result of the function, depending on how you call it and what your language offers.


Explanation in regex comment mode:

(?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.
Peter Boughton
  • 110,170
  • 32
  • 120
  • 176
3

This should do the trick.

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

The server name is in the first capturing group

jitter
  • 53,475
  • 11
  • 111
  • 124
  • 4
    At the start of a line (^), match two forward slashes (//), then one or more (+) characters that's not another forward slash ([^/]) followed by one or more occurrences of anything (.*) The parens "(" and ")" indicate a 'capturing group'. – mechanical_meat Jun 27 '09 at 17:26
  • @Adam: Thanks for explaining how the regular expression actually works. – Jason Down Jun 27 '09 at 18:04
  • 1
    @Jason: happy to do so. A mistake in my explanation: the * symbol is not 'one or more', it is 'zero or more'. The + symbol is 'one or more' – mechanical_meat Jun 27 '09 at 18:14
  • using comment 1 here I get the following in c#: //servername/ is there a way to strip off the slashes? (my program) Regex r = new Regex(@"^//(?\w+)/", RegexOptions.IgnoreCase); Match m = r.Match(@"//servername/directory/directory"); CaptureCollection cc = m.Captures; foreach (Capture c in cc) { System.Console.WriteLine(c); } – KevinDeus Jun 27 '09 at 18:18
1

Regular expression to match servername:

^//(\w+)
Alan Haggai Alavi
  • 72,802
  • 19
  • 102
  • 127
0

Ugly but it just works:

var host = uncPath.Split(new [] {'\\'}, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
smiron
  • 408
  • 3
  • 13
0

Use System.Uri Host property: https://learn.microsoft.com/en-us/dotnet/api/system.uri.host?view=net-7.0

var path = @"\\servername\d$\directory";
var uncPath = new Uri(path);
var serverName = uncPath.Host; // returns "servername"
Andrew Roberts
  • 573
  • 6
  • 7