Environment
- VB.net
- .NET core 3.1
Aim
Define a Text.Encoding
instance which defines Shift-JIS and UTF-8 without BOM.
References
Code
Dim UTF8 as Boolean
'(...)
Dim enc As System.Text.Encoding
If UTF8 Then
'UTF-8 encoding without BOM
enc = New System.Text.UTF8Encoding(False)
Else
'Shift-JIS encoding
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance)
Dim encFallBack As System.Text.DecoderReplacementFallback = New System.Text.DecoderReplacementFallback("?")
enc = System.Text.Encoding.GetEncoding("shift_jis", System.Text.EncoderFallback.ReplacementFallback, encFallBack)
End If
Note
-
New System.Text.UTF8Encoding(False)
defines UTF-8 without BOM.-
System.Text.Encoding.UTF8
seems good as well, but it returns UTF-8 with BOM, which is equivalent toNew System.Text.UTF8Encoding(true)
.
cf. Encoding.UTF8 Property (System.Text) | Microsoft Docs
-
- On .Net Frameworks, the simple code
enc = System.Text.Encoding.GetEncoding("shift_jis")
may work. However, it is not the case on .Net Core nor .Net, andRegisterProvider
is needed. - Plus, the code above replaces unencodable characters to "?", owing to
encFallBack
.