C# 如何检查一个字符串是否是合法的Http URL?

.net framework 的Uri类提供了TryCreate方法,所以可以写出下面扩展方法:

public static class StringExtensions
{
  public static bool IsUrlIsValid(this string uriName)
  {
    Uri uriResult;
    bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult)
        && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
    return result;
  }
}

测试代码:

class Program
{
  static void Main(string[] args)
  {
    System.Console.WriteLine("http://www.google.com".IsUrlIsValid());
    System.Console.WriteLine("https://www.google.com".IsUrlIsValid());
    System.Console.WriteLine("www.google.com".IsUrlIsValid());
    System.Console.WriteLine("google.com".IsUrlIsValid());
    System.Console.WriteLine("google".IsUrlIsValid());
    System.Console.WriteLine("http://www.google".IsUrlIsValid());
    System.Console.WriteLine("http://google".IsUrlIsValid());
    System.Console.WriteLine("http://google.com".IsUrlIsValid());
  }
}

输出:

True
True
False
False
False
True
True
True

参考:
How to check whether a string is a valid HTTP URL?

posted @ 2025-06-07 21:55  BigBosscyb  阅读(64)  评论(0)    收藏  举报