dotnet:encoding

Encoding クラス (System.Text)

 .NET Framework がテキストを保持する際の内部表現は Unicode UTF-16 である。 例えば、Shift-JIS形式のファイルからデータを読み込む場合、Shift-JISデコーダはShift-JISを内部表現のUTF-16に変換する。 また、Shift-JIS形式のファイルにデータを書き込む場合、エンコーダは内部形式のUTF-16をShift-JISに変換する。

 具体的には、StreamReader はファイルを内部バッファに読み込み、encoding.GetDecoder() にて取得した decoder を利用して、バッファのデータを decoder.GetChars() を使用しデコードする。
 一方 StreamWriter は encoding.GetEncoder() にて取得した encoder を利用して、内部バッファのデータを Flush する時に encoder.GetBytes() を使ってエンコードし stream に Write して Flush する。

参考文献:
 File: System.IO.StreamReader - 123aspx.com ASP.NET Resource Directory
 File: System.IO.StreamWriter - 123aspx.com ASP.NET Resource Directory

 Encoding クラスから派生した ASCIIEncoding や UTF8Encoding は、エンコーダ/デコーダが動作する規則を表している。 そのため、文字コード変換を行う処理では、Encodingを指定することによってエンコード/デコードの動作を指定できる。

クラス名説明
ASCIIEncodingUnicode文字を1個の7ビットASCII文字としてエンコードする。このエンコーディングは、U+0000~U+007Fまでの文字値だけをサポートする。コード ページは20127。
Encoding.ASCIIプロパティを通じても使用できる。
UTF7EncodingUTF-7エンコーディングを使用してUnicode文字をエンコードする。このエンコーディングは、すべてのUnicode文字値をサポートしている。コード ページは65000。
Encoding.UTF7プロパティを通じても使用できる。
UTF8EncodingUTF-8エンコーディングを使用してUnicode文字をエンコードする。このエンコーディングは、すべてのUnicode文字値をサポートしている。コード ページは65001。
Encoding.UTF8プロパティを通じて使用できる。
UnicodeEncodingUTF-16エンコーディングを使用してUnicode文字をエンコードする。リトル エンディアン(コード ページ 1200)とビッグ エンディアン(コード ページ 1201)の両方のバイト順をサポートしている。
Encoding.Unicodeプロパティ、および Encoding.BigEndianUnicodeプロパティを通じても使用できる。
UTF32EncodingUTF-32エンコーディングを使用してUnicode文字をエンコードする。リトル エンディアン(コード ページ 65005)とビッグ エンディアン(コード ページ 65006)の両方のバイト順をサポートしている。
Encoding.UTF32プロパティを通じても使用できる。
文字コードエンコーディング取得方法備考
ASCIIEncoding.ASCII
Shift-JISEncoding.GetEncoding(“shift-jis”)
EUC-JPEncoding.GetEncoding(“euc-jp”)
UTF-8Encoding.UTF8StreamReader/StreamWriterを利用する場合は、UTF-8が既定値であるため指定する必要はない。

Shift-JISファイルの読み込みの例
[VB]

Imports System
Imports System.IO
Imports System.Text
 
Module SampleAppVB
    Sub Main()
        ' Shift-JISファイルを開く
        Using sr As StreamReader = _
            New StreamReader("sjis.txt", Encoding.GetEncoding("shift-jis"))
            ' コンソール出力
            Console.WriteLine(sr.ReadToEnd())
        End Using
    End Sub
End Module

[C#]

using System;
using System.IO;
using System.Text;
 
namespace SampleApplicationCS
{
    public class SampleAppCS
    {
        static void Main(string[] args)
        {
            // Shift-JISファイルを開く
            using (StreamReader sr =
                new StreamReader("sjis.txt", Encoding.GetEncoding("shift-jis")))
            {
                // コンソール出力
                Console.WriteLine(sr.ReadToEnd());
            }
        }
    }
}

[C++]

using namespace System;
using namespace System::IO;
using namespace System::Text;
 
int main(array<System::String ^> ^args)
{
    StreamReader sr("sjis.txt", Encoding::GetEncoding("shift-jis"));
 
    // コンソール出力
    Console::WriteLine(sr.ReadToEnd());
 
    return 0;
}
  • dotnet/encoding.txt
  • 最終更新: 2019/05/18 02:23
  • by 非ログインユーザー