Encoding
개체를 가져와야합니다. ASCII는 이름이 ASCII 인 것과 같습니다. ASCII는 7 비트 ASCII 문자 만 지원합니다. 원하는 파일을 변환하는 것이면 바이트 배열을 직접 처리하는 것보다 쉽습니다. 당신이 바이트 배열을 직접 갖고 싶어
using (System.IO.StreamReader reader = new System.IO.StreamReader(fileName,
Encoding.GetEncoding("iso-8859-1")))
{
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(
outFileName, Encoding.UTF8))
{
writer.Write(reader.ReadToEnd());
}
}
그러나, 그것은 Encoding.Convert
으로 쉽게 할 충분하다.
byte[] converted = Encoding.Convert(Encoding.GetEncoding("iso-8859-1"),
Encoding.UTF8, data);
그것은 당신이 길을 가고 싶은 경우 다음 이 파일 IO에 대한 StreamReader
같은 인코딩 기반 문자열 리더를 사용하지 않도록 그러나, 여기서주의하는 것이 중요합니다. 파일의 실제 바이트를 읽으므로 FileStream
이 더 적합합니다.
완전히 문제를 탐구의 관심,이 같은 것이 작동합니다 :
using (System.IO.FileStream input = new System.IO.FileStream(fileName,
System.IO.FileMode.Open,
System.IO.FileAccess.Read))
{
byte[] buffer = new byte[input.Length];
int readLength = 0;
while (readLength < buffer.Length)
readLength += input.Read(buffer, readLength, buffer.Length - readLength);
byte[] converted = Encoding.Convert(Encoding.GetEncoding("iso-8859-1"),
Encoding.UTF8, buffer);
using (System.IO.FileStream output = new System.IO.FileStream(outFileName,
System.IO.FileMode.Create,
System.IO.FileAccess.Write))
{
output.Write(converted, 0, converted.Length);
}
}
을이 예에서 buffer
변수는 그래서 변환이 없다하는 byte[]
로 파일의 실제 데이터로 채워집니다 끝난. Encoding.Convert
은 소스 및 대상 인코딩을 지정하고 변환 된 바이트를 ... converted
이라는 변수에 저장합니다. 그런 다음 출력 파일에 직접 기록됩니다.
내가 말했듯이, StreamReader
과 StreamWriter
을 사용하는 첫 번째 옵션은이 모든 작업을 수행하는 경우 훨씬 간단하지만 후자의 예는 실제로 진행되고있는 작업에 대한 힌트를 더 많이 제공해야합니다. 파일이 (~ 10메가바이트 말), 당신은 두 줄의 코드 만 필요합니다 상대적으로 작은 경우
당신이에 밖으로 asciiString를 작성하는 UTF8 인코딩 StreamWriter를 사용하여 시도 되세요 텍스트 파일? 그럴 수 있니? – Task
@ Task : 그의 문제는 그가 8859-1에서 문자열을 얻지 못했고 UTF-8로 저장할 수 없다는 것이 아닙니다. –
오, 그건 완전히 그의 문제입니다. 필자는 Encoding.Convert 호출보다는 StreamReader/StreamWriter 쌍으로 텍스트 변환을 디버깅하는 것이 더 쉽다는 것을 알았습니다. (그래서 in/out 파일을 볼 수 있습니다.) 그건 나 뿐이야. – Task