如何在 Vb.Net 中使用 streamwriter 从字符串变量创建 csv 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25994972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:04:10  来源:igfitidea点击:

How to create a csv file from string variable using streamwriter in Vb.Net?

vb.netcsv

提问by goofyui

I am working on VS 2012, Vb.Net using .Net 4.0.

我正在使用 .Net 4.0 开发 VS 2012,Vb.Net。

Using Streamwriter or FileStream, I am trying to create a Temp csv which will be located in c:\windows\temp folder. Values for the .csv file will be populated from a string variable.

使用 Streamwriter 或 FileStream,我正在尝试创建一个位于 c:\windows\temp 文件夹中的 Temp csv。.csv 文件的值将从字符串变量填充。

Sample values in the string variable will look like as..

字符串变量中的示例值看起来像..

1,2,3,411,345
2,3,4,55,678
5,6,7,8,9999

How to write a .csv file from string variable ?

如何从字符串变量写入 .csv 文件?

Dim reader As StreamReader = New System.IO.StreamReader(File.OpenRead("D:\CSV\Test.csv"))
Dim listA As New List(Of String)()
Dim listB As New List(Of String)()
Dim s As String = ""
While Not reader.EndOfStream
    Dim line As String = reader.ReadLine()
    Dim values As String() = line.Split(";"c)
    listA.Add(values(0))
    s = s + line + Chr(10)
End While

回答by goofyui

Using Streamwriter ( sw is the variable declaration) . I am able to write .csv file.

使用 Streamwriter(sw 是变量声明)。我能够编写 .csv 文件。

 Public Sub Test()
        Try

            Dim reader As StreamReader = New System.IO.StreamReader(File.OpenRead("D:\CSV\Test.csv"))
            Dim listA As New List(Of String)()


            If File.Exists("d:\CSV\TestOut.csv") Then
                File.Delete("d:\CSV\TestOut.csv")
            End If

            Dim sw As New StreamWriter("d:\CSV\TestOut.csv")
            Dim s As String = String.Empty

            While reader.Peek() >= 0
                Dim line As String = reader.ReadLine()
                Dim values As String() = line.Split(";"c)
                listA.Add(values(0))
                s = s + line + Chr(10)
            End While
            reader.Close()
            sw.Write(s)
            sw.Close()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

    End Sub