VB.NET Tips - テキストファイル追記処理
追記元のテキストファイルを最初に全て読み込み、追記先のテキストファイルに追加書込みを行います。
テキストファイルのコードは Shift-JIS を想定していますので、エンコーディングは Shift-JIS に設定しています。
テキストファイルの読み込みには System.IO.File.ReadAllText を用います。
テキストファイルの追加書込みには System.IO.File.AppendAllText を用います。
System.IO.File.ReadAllText 関数について
Public Shared Function ReadAllText(path As String, encoding As Encoding) As String
path:
読み取り用に開かれるファイルパス。
encoding
ファイルの内容に適用されるエンコーディング。
戻り値:
ファイルのすべての行を格納している文字列。
System.IO.File.AppendAllText 関数について
Public Shared Sub AppendAllText(path As String, contents As String, encoding As Encoding)
path:
指定した文字列の追加先となるファイル。
contents
ファイルに追加する文字列。
encoding
使用する文字エンコーディング。
テキストファイル追記処理
10 | Function AppendTextFile( ByVal astrSrcFileName As String , |
11 | ByVal astrDesFileName As String ) As Boolean |
13 | AppendTextFile = False |
16 | Dim strFileText As String = "" |
17 | Dim decFileSize As Decimal = 0 |
20 | If System.IO.File.Exists(astrDesFileName) Then |
22 | decFileSize = FileLen(astrDesFileName) |
25 | If decFileSize = 0 Or decFileSize = 1 Then |
27 | My.Computer.FileSystem.CopyFile(astrSrcFileName, astrDesFileName, True ) |
30 | Dim enc As System.Text.Encoding = System.Text.Encoding.GetEncoding( "Shift_JIS" ) |
32 | strFileText = System.IO.File.ReadAllText(astrSrcFileName, enc) |
34 | System.IO.File.AppendAllText(astrDesFileName, strFileText, enc) |