VB.NETで固定長文字列を生成する。

システム間インターフェイスで固定長ファイルを扱うケースがあると思いますが、
VB.NETC#で固定長の文字列を作ろうとしても、そもそも.net framework には
標準で固定長文字列(ShiftJIS)を生成する機能が用意されていません。
全角(2バイト)文字を考慮すると、以下のような関数が必要となります。




''' -----------------------------------------------------------------------------------------
'''
''' 文字列を指定されたバイト数の固定長文字列に変換します。

'''
''' 対象となる文字列。
'''
''' バイト数(Shift-Jis)
'''
''' 固定長文字列

''' -----------------------------------------------------------------------------------------

Public Shared Function GetSJisFixedString(ByVal Str As String, _
ByVal ByteCount As Integer)

Dim wkstr As String = Str.PadRight(ByteCount)
Dim hEncoding As System.Text.Encoding = _
System.Text.Encoding.GetEncoding("Shift_JIS")
Dim btBytes As Byte() = hEncoding.GetBytes(wkstr)
wkstr = hEncoding.GetString(btBytes, 0, ByteCount)
If hEncoding.GetByteCount(wkstr) > ByteCount Then
wkstr = hEncoding.GetString(btBytes, 0, ByteCount - 1) & Space(1)
End If

Return wkstr

End Function