xcorp::When it rains, it pours.

"The nice thing about rain," said Eeyore, "is that it always stops. Eventually."

StringBuilder

文字列操作をするんなら String を素で使うより,StringBuilder を使う方がかなり速いね。

'src_pathファイルをcharsetで指定された文字コードに変換し,base64エンコードしてdest_pathファイルに保存する
Private Sub TextFileToBase64(ByVal src_path As String, ByVal dest_path As String, ByVal charset As String)
    Dim encoded_str As String = String.Empty
    Dim formatted_str As String = String.Empty
    Dim data_str As String
    Dim data_bytes As Byte() = Nothing
    Dim sr As StreamReader
    Dim sw As StreamWriter
    Try
        sr = New StreamReader(src_path, System.Text.Encoding.Default)
        data_str = sr.ReadToEnd()
        data_bytes = Encoding.GetEncoding(charset).GetBytes(data_str)
        encoded_str = Convert.ToBase64String(data_bytes)
        formatted_str = FormatBase64StringForMail(encoded_str)
        sw = New StreamWriter(dest_path, False, System.Text.Encoding.GetEncoding(charset))
        sw.Write(formatted_str)
    Catch exp As Exception
        MsgBox(exp.Message)
    Finally
        If Not (sr Is Nothing) Then
            sr.Close()
        End If
        If Not (sw Is Nothing) Then
            sw.Close()
        End If
    End Try
End Sub

'base64エンコードされた文字列をメールの標準改行位置(76文字目)で改行し、その文字列を返す
Private Function FormatBase64StringForMail(ByVal base64_str As String) As String
    Dim idx As Integer = 0
    Dim len As Integer
    Dim ret_str As String = String.Empty
    Try
        len = base64_str.Length
        Do While idx < len
            If (idx + 76) > len Then
                ret_str = ret_str + base64_str.Substring(idx) + vbCrLf
            Else
                ret_str = ret_str + base64_str.Substring(idx, 76) + vbCrLf
            End If
            idx = idx + 76
        Loop
    Catch exp As Exception
        MsgBox(exp.Message)
    End Try
    Return ret_str
End Function

FormatBase64StringForMail() メソッドはちょっと前まで String を使っていたが、どうにもこうにも遅くて、2 メガバイト弱のファイルを処理するのに 3 分以上かかっていた(;´Д`)
そこで以下のように StringBuilder を使うようにしたところ、5〜6 秒で処理が終わるようになったε=(゜∀゜)

'base64エンコードされた文字列をメールの標準改行位置(76文字目)で改行し、その文字列を返す
Private Function FormatBase64StringForMail(ByVal base64_str As String) As String
    Dim idx As Integer = 0
    Dim len As Integer
    Dim ret_str As String = String.Empty
    Dim str_bld As New StringBuilder
    Try
        len = base64_str.Length
        Do While idx < len
            If (idx + 76) > len Then
                str_bld.Append(base64_str.Substring(idx) + vbCrLf)
            Else
                str_bld.Append(base64_str.Substring(idx, 76) + vbCrLf)
            End If
            idx = idx + 76
        Loop
        ret_str = str_bld.ToString()
    Catch exp As Exception
        MsgBox(exp.Message)
    Finally
        str_bld = Nothing
    End Try
    Return ret_str
End Function