「VB.net」StreamWriterでCSVファイルに文字を書き込む

書式
1.Public Sub New (path As String, append As Boolean)
既定のエンコーディングとバッファー サイズを使用して、指定したファイル用の StreamWriter クラ スの新しいインスタンスを初期化します。

2.Public Overrides Sub WriteLine (value As String)
文字列を、続いて行終端記号をストリームに書き込みます。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Imports System.IO
Imports System.Text
Module Module1
Sub Main()
'ファイル名を指定
Dim filePath = "C:\arkgame\2021\info\resule.csv"
'List型文字列の初期化
Dim fileLst As New List(Of String)(New String() {"userA,21,test addr1", "userB,31,test addr2", "userC,41,test addr3", "userD,51,test addr4"})
Dim fileLine As String = ""
Try
'StreamWriterのインスタンスを生成 usingステートメント
Using writer As New StreamWriter(filePath, True, Encoding.GetEncoding("Shift_JIS"))
'リストの要素を書き込む 1行ずつ
For Each bb As String In fileLst
writer.WriteLine(bb)
Next
End Using
Console.WriteLine("ファイルに文字を書き込んだ")
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:\arkgame\2021\info\resule.csv" 'List型文字列の初期化 Dim fileLst As New List(Of String)(New String() {"userA,21,test addr1", "userB,31,test addr2", "userC,41,test addr3", "userD,51,test addr4"}) Dim fileLine As String = "" Try 'StreamWriterのインスタンスを生成 usingステートメント Using writer As New StreamWriter(filePath, True, Encoding.GetEncoding("Shift_JIS")) 'リストの要素を書き込む 1行ずつ For Each bb As String In fileLst writer.WriteLine(bb) Next End Using Console.WriteLine("ファイルに文字を書き込んだ") 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:\arkgame\2021\info\resule.csv"
        'List型文字列の初期化
        Dim fileLst As New List(Of String)(New String() {"userA,21,test addr1", "userB,31,test addr2", "userC,41,test addr3", "userD,51,test addr4"})

        Dim fileLine As String = ""

        Try
            'StreamWriterのインスタンスを生成 usingステートメント
            Using writer As New StreamWriter(filePath, True, Encoding.GetEncoding("Shift_JIS"))

                'リストの要素を書き込む 1行ずつ
                For Each bb As String In fileLst
                    writer.WriteLine(bb)
                Next
            End Using
            Console.WriteLine("ファイルに文字を書き込んだ")
        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try

        Console.ReadKey()

    End Sub

End Module

resule.csvの中身結果
userA,21,test addr1
userB,31,test addr2
userC,41,test addr3
userD,51,test addr4

VB.net

Posted by arkgame