Gopal Gopal - 2 months ago 10x 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


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