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

C# Uri.EscapeDataString() 메서드 – 문자열 이스케이프 처리 방법

C#의 Uri.EscapeDataString() 메서드는 문자열을 이스케이프(escape)된 표현으로 변환하는 정적 메서드입니다. URL에 그대로 사용할 수 없는 특수 문자나 공백 등을 백분율 인코딩(percent-encoding) 형태로 변환하여, 데이터를 안전하게 전송하거나 URI에 포함시킬 수 있도록 도와줍니다.

구문

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

public static string EscapeDataString(string str);

여기서 매개변수 str은 이스케이프 처리할 대상 문자열을 의미합니다.

예제

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

using System;
public class Demo {
   public static void Main(){
      string URI1 = "https://www.tutorialspoint.com/index.htm";
      Console.WriteLine("URI = "+URI1);
      string URI2 = "https://www.tutorialspoint.com/";
      Console.WriteLine("URI = "+URI2);
      Console.WriteLine("
Escaped string (URI1) = "+Uri.EscapeDataString(URI1));
      Console.WriteLine("Escaped string (URI2) = "+Uri.EscapeDataString(URI2));
   }
}

실행 결과

위 프로그램을 실행하면 다음과 같은 결과가 출력됩니다.

URI = https://www.tutorialspoint.com/index.htm
URI = https://www.tutorialspoint.com/
Escaped string (URI1) = https%3A%2F%2Fwww.tutorialspoint.com%2Findex.htm
Escaped string (URI2) = https%3A%2F%2Fwww.tutorialspoint.com%2F

결과 분석

출력 결과를 보면 원본 URI의 콜론(:)은 %3A로, 슬래시(/)는 %2F로 각각 변환된 것을 확인할 수 있습니다. 이처럼 EscapeDataString() 메서드는 URI에서 특별한 의미를 가지는 문자들을 모두 인코딩하기 때문에, 쿼리 문자열이나 폼 데이터를 전송할 때 발생할 수 있는 오류를 예방하는 데 유용하게 활용됩니다.