Gopal Gopal - 1 year ago 82 Question

Writing a text file

I am using VB.NET and SQL Server 2005, and I want to write a text file from the database like.

Open a text file, read the data from the database then write into the text file.


cmd = New SqlCommand("SELECT ID, Name, Dept from table", con)
dr = cmd.ExecuteReader

While dr.Read()

Dim data As String
data = File.ReadAllText(dr.Item("PersonID"))
File.WriteAllText("D:\test.txt", data)
End While

The above code is showing error, How to write a text file

VB.NET Code Help

Answer Source

In your code you are not actually reading from the database. Try this:

Using writer = New StreamWriter("d:\test.txt")
    While dr.Read()
        Dim id = dr.GetInt32(0)
        Dim name = dr.GetString(1)
        Dim dept = dr.GetString(2)

        writer.WriteLine(String.Format("{0} {1} {2}", id, name, dept))
    End While
End Using
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download