可以创建csv但不能写入它

时间:2017-04-06 20:38:53

标签: wpf vb.net csv

我的问题类似于post。我可以创建csv,但一旦创建它就无法写入。但与那篇文章不同,我不是两次创建文件。

我的代码:

Dim path As String = "C:\xxx\yyy\" & csvFileName

If File.Exists(path) = False Then
    ' Create a file to write to.
    Dim createText As String = String.Empty + Environment.NewLine
    File.WriteAllText(path, createText)
End If


Dim sw As StreamWriter = New StreamWriter(csvFileName, True)

'first, write all column names to csv.
Dim sb As New StringBuilder
For Each col As DataColumn In dt.Columns
    sb.Append(col.ColumnName)
Next
sw.Write(sb.ToString)

'now, write rows to csv.
For Each row As DataRow In dt.Rows
    sb = New StringBuilder

    For Each col As DataColumn In dt.Columns
        sb.Append(row(col.ColumnName))
    Next

    sw.Write(sb.ToString)
Next

sw.Close()

感谢任何帮助。感谢。

2 个答案:

答案 0 :(得分:2)

您在此处使用两个不同的文件名。 StreamWriter应写入path而不是csvFileName

Dim sw As StreamWriter = New StreamWriter(path, True)

答案 1 :(得分:1)

There are many problem in your code

  1. you are not writing column delimiter
  2. you are using file name instead of the full path
  3. you are using sw.Write() method instead of sw.WriteLine() (all text will be writed on one line)

you can use the following code:

    Dim path As String = "C:\xxx\yyy\" & csvFileName

    If File.Exists(path) = False Then
    ' Create a file to write to.
        Dim createText As String = String.Empty + Environment.NewLine
        File.WriteAllText(path, createText)
    End If


    Using sw As StreamWriter = New StreamWriter(path, True)

        'first, write all column names to csv.
        Dim sb As New StringBuilder

        For Each col As DataColumn In dt.Columns
            sb.Append(col.ColumnName & ",")
        Next

        sw.WriteLine(sb.ToString)

        'now, write rows to csv.
        For Each row As DataRow In dt.Rows
            sb = New StringBuilder

            For Each col As DataColumn In dt.Columns
                sb.Append(row(col.ColumnName).ToString  & ",")
            Next

            sw.WriteLine(sb.ToString)
        Next

        sw.Close()

    End Using