How to pull the server name from a UNC

前端 未结 5 839
借酒劲吻你
借酒劲吻你 2021-02-05 16:34

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 nee

相关标签:
5条回答
  • 2021-02-05 16:49

    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) + "/";
    
    0 讨论(0)
  • 2021-02-05 16:52

    Regular expression to match servername:

    ^//(\w+)
    
    0 讨论(0)
  • 2021-02-05 17:03

    Ugly but it just works:

    var host = uncPath.Split(new [] {'\\'}, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
    
    0 讨论(0)
  • 2021-02-05 17:06

    This should do the trick.

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

    The server name is in the first capturing group

    0 讨论(0)
  • 2021-02-05 17:09

    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.
    
    0 讨论(0)
提交回复
热议问题