我有一个VB Visual Studio 2012项目,我在其中创建.csv文件。以下是摘录。基本上,当我调试程序时,它会按预期在bin / debug中创建.csv文件。但是,当我发布程序时,我无法弄清楚我的生活在哪里或为什么不创建它们。我已将构建输出路径更改为几个不同的时间,并确保我在其“发布”部分。我甚至不关心输出的位置,我只是想在某个地方!感谢
编辑:好的,所以我找到了文件... C:\ Users \ ah0169569 \ AppData \ Local \ Apps \ 2.0 \ BLWZBB1R.02J \ XTOQVPX5.N3O \ payr..tion_d 310a0976fa1c317_0001.0000_81024c9c62a3db84 所以这是一个愚蠢的位置。如何将输出更改为我的应用程序文件夹?或者用户指定的地方?
Sub DataTable2CSV(ByVal table As DataTable, ByVal filename As String)
DataTable2CSV(table, filename, ",")
End Sub
Sub DataTable2CSV(ByVal table As DataTable, ByVal filename As String, _
ByVal sepChar As String)
Dim writer As System.IO.StreamWriter
Try
writer = New System.IO.StreamWriter(filename)
' first write a line with the columns name
Dim sep As String = ""
Dim builder As New System.Text.StringBuilder
For Each col As DataColumn In table.Columns
builder.Append(sep).Append(col.ColumnName)
sep = sepChar
Next
writer.WriteLine(builder.ToString())
' then write all the rows
For Each row As DataRow In table.Rows
sep = ""
builder = New System.Text.StringBuilder
For Each col As DataColumn In table.Columns
builder.Append(sep).Append(row(col.ColumnName))
sep = sepChar
Next
writer.WriteLine(builder.ToString())
Next
Finally
If Not writer Is Nothing Then writer.Close()
End Try
End Sub
答案 0 :(得分:1)
首先要在代码中更改Try / Finally。通过这种方式,您永远不会知道您的代码是否失败以及失败的原因。我添加了一个Catch和一个MessageBox来显示是否有错误
Try
Using writer = New System.IO.StreamWriter(filename)
Dim builder As New System.Text.StringBuilder
For Each col As DataColumn In table.Columns
builder.Append(col.ColumnName + sepChar)
Next
builder.Length -= 1
builder.AppendLine()
For Each row As DataRow In table.Rows
For Each col As DataColumn In table.Columns
builder.Append(row(col.ColumnName) + sepChar)
Next
builder.Length -= 1
builder.AppendLine()
Next
writer.Write(builder.ToString())
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
接下来就是Using Statement确保在异常的情况下正确关闭你的Stream。 最新修复了您使用StringBuilder来累积文本并在一次调用中编写所有内容。当然这对小数据来说不是问题。