指定されたテキストファイルを読み込み指定でオープンし、一時ファイルを作成し、その一時ファイルを追加指定でオープンします。 読込ファイルの1行目をスキップする様にフラグ処理を行い、順次1行毎に一時ファイルに書込みます。
最終的に、一時ファイルを読込ファイルに上書きコピーし、一時ファイルを削除します。 テキストファイルのコードは Shift-JIS を想定していますので、エンコーディングは Shift-JIS に設定しています。
テキストファイルの読み込みには System.IO.StreamReader クラスを用います。
テキストファイルの追加書込みには System.IO.StreamWriter クラスを用います。
テキストファイル先頭行削除処理
''' -----------------------------------------------------------------------
'''
''' テキストファイル先頭行削除処理
'''
''' <param name="astrSrcFileName">処理データファイル名</param>
''' 正常終了:true エラー発生:false
''' -----------------------------------------------------------------------
Private Function DeleteTopTextFile(ByVal astrSrcFileName As String) As Boolean
'戻り値初期化
DeleteTopTextFile = False
Dim sr As System.IO.StreamReader = Nothing
Dim sw As System.IO.StreamWriter = Nothing
Try
'ファイルを読み込みで開く
Dim enc As System.Text.Encoding = System.Text.Encoding.GetEncoding("shift_jis")
sr = New System.IO.StreamReader(astrSrcFileName, enc)
'一時ファイルを作成する
Dim tmpPath As String = System.IO.Path.GetTempFileName()
'一時ファイルを書き込みで開く
sw = New System.IO.StreamWriter(tmpPath, True, enc)
'先頭フラグON
Dim blnFirstLine As Boolean = True
'テキストを一行ずつ読込
While sr.Peek() > -1
'一行読込
Dim line As String = sr.ReadLine()
'先頭行スキップ
If blnFirstLine = True Then
'先頭フラグONの場合、OFFしてスキップ
blnFirstLine = False
Continue While
End If
'一時ファイル書込
sw.WriteLine(line)
End While
'閉じる
sr.Close()
sw.Close()
sr = Nothing
sw = Nothing
'一時ファイルと入れ替える
System.IO.File.Copy(tmpPath, astrSrcFileName, True) 'OverWrite
System.IO.File.Delete(tmpPath)
'正常終了
DeleteTopTextFile = True
Catch ex As Exception
'エラー処理が必要な場合は、ここに記述する
Finally
If sr IsNot Nothing Then
sr.Close()
sr = Nothing
End If
If sw IsNot Nothing Then
sw.Close()
sw = Nothing
End If
End Try
End Function
関連する記事
⇒フォルダコピー(サブフォルダ以下も含む):[Directory.GetFiles,Directory.GetDirectories]⇒指定フォルダ内の全ファイルを削除 :[Directory.GetFiles,File.Delete]
⇒指定フォルダ内の全ファイルをクリア :[Directory.GetFiles,File.Delete]
⇒テキストファイル追記処理 :[File.ReadAllText,File.AppendAllText]
⇒ファイルサイズ取得 :[IO.FileInfo]
⇒テキストファイルレコード件数取得 :[IO.StreamReader]
⇒ファイル上書きコピー :[IO.FileInfo,File.Copy]
PR
コメント