Microsoft MVP성태의 닷넷 이야기
.NET Framework: 350. String 데이터를 Stream으로 변환하는 방법 [링크 복사], [링크+제목 복사],
조회: 23796
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

String 데이터를 Stream으로 변환하는 방법

사실 이게 하나의 글로 씌여지기에는 좀 단순한 문제이긴 합니다. ^^

검색만 해보면 다음과 같은 식으로 2가지 방법이 나오는데요.

// 방법 1: Encoding 타입 사용
string test = "ab";

byte[] byteArray = Encoding.UTF8.GetBytes(test);
MemoryStream stream1 = new MemoryStream(byteArray);

// 방법 2: StreamWriter 사용
MemoryStream stream2 = new MemoryStream();
StreamWriter sw = new StreamWriter(stream2, Encoding.UTF8);
sw.Write(test);
sw.Flush();
stream2.Position = 0;

그런데, 전자와 후자는 결과가 틀립니다. 실제로 한번 출력을 해볼까요? ^^

foreach (byte aByte in stream1.ToArray())
{
    Console.Write(aByte.ToString("x") + ", ");
}

Console.WriteLine();

foreach (byte aByte in stream2.ToArray())
{
    Console.Write(aByte.ToString("x") + ", ");
}

// 출력 결과
61, 62,
ef, bb, bf, 61, 62,

보시는 것처럼 StreamWriter는 3바이트가 더 출력됩니다. 이게 뭔지 혹시 감이 오세요? ^^ 그렇습니다. StreamWriter는 BOM(Byte Order Mark)을 함께 출력합니다.

보통 이것이 문제가 되지 않을 수 있지만, BOM 인식을 간과하는 특정 클래스가 있다면 상황이 달라집니다. 바로 DataContractJsonSerializer가 그 예입니다. 예를 들어, 아래와 같이 stream을 건네주면,

public class Test
{
    public string id { get; set; }
}

string test = "{ \"id\": \"ab\" }";

MemoryStream stream2 = ...[BOM을 쓰는 방식]...;

DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(Test));
Test user2 = dcjs.ReadObject(stream2) as Test;

BOM 데이터를 해석하려고 시도하는 바람에 "System.Runtime.Serialization.SerializationException" 예외가 발생합니다.

System.Runtime.Serialization.SerializationException was unhandled
  HResult=-2146233076
  Message=There was an error deserializing the object of type ConsoleApplication1.Test. Encountered unexpected character 'i'.
  Source=System.Runtime.Serialization
  StackTrace:
       at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
       at System.Runtime.Serialization.Json.DataContractJsonSerializer.ReadObject(XmlDictionaryReader reader)
       at System.Runtime.Serialization.Json.DataContractJsonSerializer.ReadObject(Stream stream)
       at ConsoleApplication1.Program.Main(String[] args) in d:\...\Program.cs:line 45
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
		...[생략]...
  InnerException: System.Xml.XmlException
       HResult=-2146232000
       Message=Encountered unexpected character 'i'.
       Source=System.Runtime.Serialization
       LineNumber=0
       LinePosition=0
       StackTrace:
            at System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader reader, XmlException exception)
            at System.Runtime.Serialization.Json.XmlJsonReader.ReadAttributes()
            ...[생략]...
            at System.Runtime.Serialization.XmlObjectSerializer.InternalReadObject(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
            at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
       InnerException: 

물론, "Encoding.UTF8.GetBytes"를 이용하여 BOM을 제거한 stream을 넘겨주면 오류가 발생하지 않습니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 10/28/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2014-06-11 03시56분
[김영준] 인코딩 설정시 BOM을 설정을 지정할 수도 있습니다. ^^

bool isBOM = false;
StreamWriter sw = new StreamWriter(stream2, new UTF8Encoding(isBOM) );
[guest]
2014-06-11 11시52분
@김영준 좋은 의견 감사드립니다. ^^
정성태

... 16  [17]  18  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13516정성태1/7/20249691닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
13515정성태1/6/20249636닷넷: 2195. async 메서드 내에서 C# 7의 discard 구문 활용 사례 [1]
13514정성태1/5/20249530개발 환경 구성: 702. IIS - AppPool의 "Disable Overlapped Recycle" 옵션
13513정성태1/5/20249627닷넷: 2194. C# - WebActivatorEx / System.Web의 PreApplicationStartMethod 특성
13512정성태1/4/20249896개발 환경 구성: 701. IIS - w3wp.exe 프로세스의 ASP.NET 런타임을 항상 Warmup 모드로 유지하는 preload Enabled 설정
13511정성태1/4/20249624닷넷: 2193. C# - ASP.NET Web Application + OpenAPI(Swashbuckle) 스펙 제공
13510정성태1/3/20249371닷넷: 2192. C# - 특정 실행 파일이 있는지 확인하는 방법 (Linux)
13509정성태1/3/202410554오류 유형: 887. .NET Core 2 이하의 프로젝트에서 System.Runtime.CompilerServices.Unsafe doesn't support netcoreapp2.0.
13508정성태1/3/202410043오류 유형: 886. ORA-28000: the account is locked
13507정성태1/2/202411129닷넷: 2191. C# - IPGlobalProperties를 이용해 netstat처럼 사용 중인 Socket 목록 구하는 방법파일 다운로드1
13506정성태12/29/202310275닷넷: 2190. C# - 닷넷 코어/5+에서 달라지는 System.Text.Encoding 지원
13505정성태12/27/202312106닷넷: 2189. C# - WebSocket 클라이언트를 닷넷으로 구현하는 예제 (System.Net.WebSockets)파일 다운로드1
13504정성태12/27/202311222닷넷: 2188. C# - ASP.NET Core SignalR로 구현하는 채팅 서비스 예제파일 다운로드1
13503정성태12/27/202310400Linux: 67. WSL 환경 + mlocate(locate) 도구의 /mnt 디렉터리 검색 문제
13502정성태12/26/202310940닷넷: 2187. C# - 다른 프로세스의 환경변수 읽는 예제파일 다운로드1
13501정성태12/25/202310275개발 환경 구성: 700. WSL + uwsgi - IPv6로 바인딩하는 방법
13500정성태12/24/202310786디버깅 기술: 194. Windbg - x64 가상 주소를 물리 주소로 변환
13498정성태12/23/202312458닷넷: 2186. 한국투자증권 KIS Developers OpenAPI의 C# 래퍼 버전 - eFriendOpenAPI NuGet 패키지
13497정성태12/22/202310638오류 유형: 885. Visual Studiio - error : Could not connect to the remote system. Please verify your connection settings, and that your machine is on the network and reachable.
13496정성태12/21/202310558Linux: 66. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (gdb)
13495정성태12/20/202310805Linux: 65. clang++로 공유 라이브러리의 -static 옵션 빌드가 가능할까요?
13494정성태12/20/202310897Linux: 64. Linux 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency) - 두 번째 이야기
13493정성태12/19/202310992닷넷: 2185. C# - object를 QueryString으로 직렬화하는 방법
13492정성태12/19/202310384개발 환경 구성: 699. WSL에 nopCommerce 예제 구성
13491정성태12/19/20239384Linux: 63. 리눅스 - 다중 그룹 또는 사용자를 리소스에 권한 부여
13490정성태12/19/202310107개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
... 16  [17]  18  19  20  21  22  23  24  25  26  27  28  29  30  ...