|
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim path As String = "D:\Test.CSV" '対象ファイル
Dim buffer() As Byte = New Byte(0 To 49) {} '1行以上収まるサイズを指定
Dim filesize As Long = 0
Dim tempPath As String = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(path), System.IO.Path.GetRandomFileName)
Const ONEREADSIZE As Long = 1024 '一度に読み込む量
Using ifs As New System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read)
'ファイル読み込み位置を最終からバッファ分取得位置まで移動
ifs.Seek(ifs.Length - buffer.Length, System.IO.SeekOrigin.Begin)
'ファイル最終位置からバッファ分取得
ifs.Read(buffer, 0, buffer.Length)
Dim p As Long = buffer.Length - 1
Dim IsNewline As Boolean = False
Do Until IsNewline Or p < 1
'改行コード検索(CRLF=13,10)
If buffer(p - 1) = 13 And buffer(p) = 10 Then
If p <> buffer.Length - 1 Then
IsNewline = True
End If
End If
p -= 1
Loop
If IsNewline = True Then
'filesize = ifs.Length - buffer.Length + p '末尾のCRLFを消す場合
filesize = ifs.Length - buffer.Length + p + 2 '末尾のCRLFを消さない場合
'ファイル読み込み位置を先頭に移動
ifs.Seek(0, System.IO.SeekOrigin.Begin)
Using ofs As New System.IO.FileStream(tempPath, System.IO.FileMode.Create, System.IO.FileAccess.Write)
Do Until filesize <= 0
buffer = New Byte(0 To Math.Min(ONEREADSIZE - 1, filesize - 1)) {}
ifs.Read(buffer, 0, buffer.Length)
ofs.Write(buffer, 0, buffer.Length)
filesize -= buffer.Length
Loop
End Using
End If
End Using
'ファイル削除
System.IO.File.Delete(path)
'ファイル名変更
System.IO.File.Move(tempPath, path)
End Sub
|