Skip to content

Insert information into a CSV file

Rami Masri

Asked Apr 4, 2008, 2:26 PM EDT4 answers
Share
LinkedInX

Hi guys,

Alright I'm writing this VB 2005 program for work and i'm stuck at one part only.  I need to write to a CSV file.  I've been doing some digging around for 2 days; I know that it's better coding to use ADO.Net instead of streaming (not sure whether i should use oledb or odbc though .. it doesn't matter i guess) and I know how to read from a CSV file but can't find anything on how to write to it.  So I would appreciate any help in this matter. 

The CSV file contains 6 columns; line# (which will need to be incremented), version #, minor version #, description, and 2 other columns which i can't remember the titles to.

Here's the code I have so far

Imports System.Data
Imports System.Data.OleDb
Imports ADODB

VB.NET
Dim sConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\test\VCS;Extended Properties=Text;"
Dim conn As New OleDbConnection(sConnectionString)
Dim objAdapter1 As New OleDbDataAdapter()
Dim StrCmdInsert As New OleDbCommand("INSERT INTO test.csv VALUES (12, 2, 0.2, , eG3.2)", conn)  (the 12 needs to be incremented I guess .. i.e. previous+1)
conn.Open()
 objAdapter1.InsertCommand = StrCmdInsert
 StrCmdInsert.ExecuteNonQuery()
 conn.Close()

Thank you very much in advance for all the help.

4 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • Mike Gold
    0

    Use WriteStream.  It's easier and more flexible.  You can wrap your WriteStream in a CSV Writer class so the coding practice is more sound.  I would not use ADO.NET to write out a CSV file. 

    Another approach I've taken if my data is sitting in a DataSet is to write the DataSet out as a DiffGram (the Write method of the DataSet)  and then use XSL to transform to CSV.

    0
  • 0

    Ok so I tried using streamline to write to the CSV file, the program runs through with no problems.  Although when i open the file in notepad the file is still empty i.e. nothing is being written to it. Here is my code ... am i missing anything in there?

    Dim sw As New StreamWriter("c:\test\VCS\test.csv", True)

    sw.WriteLine("12,2,0.2,0,0,eG3.2")

    sw.Close()

    0
  • Mike Gold
    0
    looks okay to me.  did you try deleting the file and rerunning? Is it throwing an exception before the close?
    0
  • 0

    Nevermind lol I closed the application down and reopened it and that solved whatever was wrong i guess.  Thanks for the help guys.

    0