Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C# Uri.IsWellFormedOriginalString() 메서드 – URI 문자열 형식 검증 방법

C#의 Uri.IsWellFormedOriginalString() 메서드는 Uri 객체를 생성할 때 사용된 문자열이 올바른 형식(well-formed)인지, 그리고 추가적인 이스케이프(escape) 처리가 필요하지 않은지 여부를 확인합니다. 이 메서드는 URI 문자열의 유효성을 검사해야 할 때 유용하게 활용됩니다.

구문

메서드의 기본 구문은 다음과 같습니다.

public bool IsWellFormedOriginalString();

반환값은 bool 타입으로, 원본 문자열이 올바른 형식이면 true, 그렇지 않으면 false를 반환합니다.

예제

이제 Uri.IsWellFormedOriginalString() 메서드를 실제로 구현한 예제를 살펴보겠습니다.

using System;
public class Demo {
   public static void Main(){
      Uri newURI1 = new Uri("https://www.tutorialspoint.com/index.htm");
      Console.WriteLine("URI = "+newURI1);
      Uri newURI2 = new Uri("https://www.qries.com/");
      Console.WriteLine("URI = "+newURI2);
      if(newURI1.Equals(newURI2))
         Console.WriteLine("두 URI는 동일합니다!");
      else
         Console.WriteLine("두 URI는 동일하지 않습니다!");
      if(newURI1.IsWellFormedOriginalString())
         Console.WriteLine("newURI1은 올바른 형식입니다!");
      else
         Console.WriteLine("newURI1은 올바른 형식이 아닙니다!");
   }
}

실행 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

URI = https://www.tutorialspoint.com/index.htm
URI = https://www.tutorialspoint.com/
Both the URIs aren't equal!
newURI1 is well formed!

출력 결과에서 볼 수 있듯이, 두 URI는 서로 다르며 newURI1에 사용된 원본 문자열은 올바른 형식임을 확인할 수 있습니다. 이처럼 IsWellFormedOriginalString() 메서드를 활용하면 URI 생성 시 전달된 문자열의 유효성을 손쉽게 검증할 수 있습니다.