Exporting Tables From .mdf file Visual Studio VB.NET

Hello experts,

I'm building an application thats linked to a .mdf file and I want to export the data out from one of the tables as a .csv file into a folder called Export Files in the current project path

I have some code I've used in Access and I'm trying to update it into VB.NET in Visual Studio 2008.

Any Ideas on how to change it, I'm having problems.

Dim getTables As String
 Dim csvName As String
 Dim BoatName As String
 'Copies the tblSurveys
 BoatName = Form!lblBoatName.Caption
 getTables = "tblSurveys"
 csvName = CurrentProject.Path & "\" & "Export Files\" & BoatName & getTables & ".csv"
 DoCmd.TransferText transfertype:=acExportDelim, _
   specificationname:="tblSurveys Export Specification", _
   tableName:=getTables, _
   filename:=csvName, _

Open in new window

Who is Participating?
aibusinesssolutionsConnect With a Mentor Commented:
First off, you have to attach the MDF file to a SQL Server, VS 2008 should have come with SQL Express 05 or 08.

Once you have the database attached, you can connect to it using a SqlCommand.  With the SqlCommand pull the data from the table, and loop through it with a SqlDataReader.

On each read, write the output to a filestream in .CSV format.  I'm just going to throw together some code.

Here you go:

Dim fs As New IO.FileStream("test.csv", IO.FileMode.CreateNew, IO.FileAccess.Write)
Dim sw As New IO.StreamWriter(fs)
Dim conn As New Data.SqlClient.SqlConnection("connection string")
Dim cmd As New Data.SqlClient.SqlCommand("Command Text", conn)
Dim dr As Data.SqlClient.SqlDataReader = cmd.ExecuteReader()
While dr.Read()
  sw.WriteLine("{0},{1},{2},{3}", dr(0), dr(1), dr(2), dr(3))
End While

Open in new window

davecocksAuthor Commented:
Hi Thanks for your help you put me on the right track.

I found another link with some suggestions if any one else needs some help.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.