「VB.NET」StreamReaderでCSVファイルを読み込む
書式
Using reader As New StreamReader(ファイル名, 文字エンコーディング)
1.Public Sub New (path As String, encoding As Encoding)
文字エンコーディングを設定して、指定したファイル名用の StreamReader クラスの新しいインスタンスを初期化します。
2.ReadLine()
現在のストリームから 1 行分の文字を読み取り、そのデータを文字列として返します。
使用例
Imports System.IO
Imports System.Text
Module Module1
Sub Main()
'ファイルパス変数の定義
Dim filePath = "C:\changfatun\2021\info\test01.csv"
Dim fileLst As New List(Of String)
Dim fileLine As String = ""
Try
'StreamReaderのインスタンスを生成
Using reader As New StreamReader(filePath, Encoding.GetEncoding("Shift_JIS"))
fileLine = reader.ReadLine()
'while文で行を読み込む
While fileLine IsNot Nothing
'リストに行の内容を追加
fileLst.Add(fileLine)
'行の内容を読み込む
fileLine = reader.ReadLine()
End While
End Using
'リストの内容を取得して出力
For Each bb As String In fileLst
Console.WriteLine(bb)
Next
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Console.ReadKey()
End Sub
End Module
Imports System.IO
Imports System.Text
Module Module1
Sub Main()
'ファイルパス変数の定義
Dim filePath = "C:\changfatun\2021\info\test01.csv"
Dim fileLst As New List(Of String)
Dim fileLine As String = ""
Try
'StreamReaderのインスタンスを生成
Using reader As New StreamReader(filePath, Encoding.GetEncoding("Shift_JIS"))
fileLine = reader.ReadLine()
'while文で行を読み込む
While fileLine IsNot Nothing
'リストに行の内容を追加
fileLst.Add(fileLine)
'行の内容を読み込む
fileLine = reader.ReadLine()
End While
End Using
'リストの内容を取得して出力
For Each bb As String In fileLst
Console.WriteLine(bb)
Next
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Console.ReadKey()
End Sub
End Module
Imports System.IO Imports System.Text Module Module1 Sub Main() 'ファイルパス変数の定義 Dim filePath = "C:\changfatun\2021\info\test01.csv" Dim fileLst As New List(Of String) Dim fileLine As String = "" Try 'StreamReaderのインスタンスを生成 Using reader As New StreamReader(filePath, Encoding.GetEncoding("Shift_JIS")) fileLine = reader.ReadLine() 'while文で行を読み込む While fileLine IsNot Nothing 'リストに行の内容を追加 fileLst.Add(fileLine) '行の内容を読み込む fileLine = reader.ReadLine() End While End Using 'リストの内容を取得して出力 For Each bb As String In fileLst Console.WriteLine(bb) Next Catch ex As Exception Console.WriteLine(ex.Message) End Try Console.ReadKey() End Sub End Module