ヘッダー
C# サンプル集
 

Base64にエンコードする

2022/12/18

→ Visual Basic のサンプルに切り替える → Python のサンプルに切り替える

 

文字列をUTF-8としてBase64にエンコードする

string value = "徳川家康ABC";
string base64 = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(value));
System.Diagnostics.Debug.WriteLine(base64); //5b6z5bed5a625bq3QUJD

Debug.WriteLineが表示される場所

 

 

文字列をShift_JISとしてBase64にエンコードする

#if NETCOREAPP
//.NET CoreでShift_JISなど追加のエンコーディングを扱うために必要です。
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
#endif

string value = "徳川家康ABC";
string base64 = Convert.ToBase64String(System.Text.Encoding.GetEncoding("Shift_JIS").GetBytes(value));
System.Diagnostics.Debug.WriteLine(base64); //k7+Q7InGjU5BQkM=

Debug.WriteLineが表示される場所

 

 

オブジェクトをBase64にエンコードする

オブジェクトの一例として、List<string> をBase64にする例。

var values = new List<string> { "Apple","徳川家康","12345" };

string json = System.Text.Json.JsonSerializer.Serialize(values);
string base64 = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(json));

//WyJBcHBsZSIsIlx1NUZCM1x1NURERFx1NUJCNlx1NUVCNyIsIjEyMzQ1Il0=
System.Diagnostics.Debug.WriteLine(base64);

Debug.WriteLineが表示される場所

メモ:この例ではオブジェクトをJSON形式で文字列化したものをBase64にしています。

メモ:List<string>に限らず、JsonSerializerでJSON化できるオブジェクトはこの例が通用します。

 

 

バイト型の配列をBase64にエンコードする

byte[] bytes = new byte[] { 0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0 };

string base64 = Convert.ToBase64String(bytes);
System.Diagnostics.Debug.WriteLine(base64); //EjRWeJq83vA=

Debug.WriteLineが表示される場所