【问题标题】:Class to recognize Port from string从字符串中识别端口的类
【发布时间】:2019-07-05 10:04:36
【问题描述】:

我有一种方法可以获取不同形式的网址,例如

foo.bar.com:5678

我需要像这样把端口弄出来

System.Uri foo = new Uri("foo.bar.com:5678");
int port = foo.Port;

但它总是返回 -1 而不是 5678

【问题讨论】:

标签: c# string url


【解决方案1】:

为字符串添加协议或使用自定义方法自行拆分:

static readonly char[] s_splitter = new char[1] { ':' };
static int GetPort(string s)
{
    int port = -1;
    if (string.IsNullOrEmpty(s))
        return port;

    string[] parts = s.Split(s_splitter);
    if (parts.Length == 2)
        int.TryParse(parts[1], out port);
    return port;
}

如果您使用的是 .NET Core 或 System.Memory NuGet 包,则无需分配任何其他字符串即可检索端口:

static int GetPort(string s)
{
    int port = -1;
    if (string.IsNullOrEmpty(s))
        return port;

    ReadOnlySpan<char> span = s;
    int index = span.IndexOf(':');
    if (index == -1 || s.Length < index)
        return port;

    int.TryParse(span.Slice(index + 1), out port);
    return port;
}

【讨论】:

    【解决方案2】:

    要从 URI 中获取 port,它要求 URI 有 protocol

    https://rextester.com/TRDAKO93228

    public class Program
    {
        public static void Main(string[] args)
        {
           System.Uri foo1 = new Uri("foo.bar.com:5678");
            int port1 = foo1.Port;  // it will return -1 as no protocol specified.
            System.Uri foo2 = new Uri("http://foo.bar.com:5678");
            int port2 = foo2.Port;  // it will return 5678
            System.Uri foo3 = new Uri("ftp://foo.bar.com:5678");
            int port3 = foo3.Port;  // it will return 5678
            System.Uri foo4 = new Uri("https://foo.bar.com");
            int port4 = foo4.Port;  // it will return 443 - default for HTTPS
            Console.WriteLine(port1);
            Console.WriteLine(port2);
            Console.WriteLine(port3);
            Console.WriteLine(port4);
        }
    }
    

    如果你有没有协议的简单字符串,你可以在前面加上 http://ftp:// 或其他,但请记住,如果你在前面加上协议并且你的 URI 没有端口,它将返回默认端口该协议。(注意端口4)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-25
      • 2013-07-15
      相关资源
      最近更新 更多