0

How to: Write Text to Files in Visual Basic

I am trying to use this procedure to export data from a datatable into a csv file. I have got the data from the table ready in a string and am trying to use the following code to write in to a file (I did want to use excel, but gave up so trying to use a csv file). I am not getting an error, but the file is not appearing either, my string is definitly not empty though. Any help/direction appreciated.

Dim str As New StringBuilder
        For Each dr As DataRow In objDS.Tables("dt_export").Rows
            For Each field As Object In dr.ItemArray
                str.Append(field.ToString & ",")
            Next
            str.Replace(",", vbNewLine, str.Length - 1, 1)
        Next
        Try
            Response.Write(str.ToString)
            My.Computer.FileSystem.WriteAllText("C:\temp\testcsv.csv", str.ToString, False)

        Catch ex As Exception
            Response.Write("Write Error")
        End Try
PowerStat
  • 3,757
  • 8
  • 32
  • 57
Barry
  • 63
  • 7
  • Start with just this: `My.Computer.FileSystem.WriteAllText("C:\temp\testcsv.csv", String.Empty, False)` and see what happens. The file should be created (it was on my computer when I tried it). I would work backwards from there, i.e. get rid of the try/catch block for the time being and see what happens. It shouldn't matter if there isn't any text in the string. – rory.ap Jan 10 '14 at 12:00
  • thank you, i have treid that. Any other ideas? If it was a permissions error, would it give me an error message? – Barry Jan 10 '14 at 12:48
  • just to confirm this definitely is looking at the c drive on my remote machine rather then the web server? – Barry Jan 10 '14 at 12:49
  • @Barry: if you execute the code above in a web application, the path will point to the server file system. – Markus Jan 10 '14 at 13:14
  • thanks Markus, i have changed it to a set location on the F drive that i have access to on the web server and it is now working. I guess my next question is how to now get the file transfered to a location on the user local PC? do i need to add on another function or do i need to take a different approach? – Barry Jan 10 '14 at 13:36
  • My.Computer.FileSystem.WriteAllText("F:\ccmi4\asp\db\uploads\" & filename & ".csv", str.ToString, False) lbl_export.text = "Open File" – Barry Jan 10 '14 at 19:50
  • i have added the above which basically puts a link to the file in to a label, which works, but it is a bit ugly. the user clicks a button (which creates the file and generates the link), then clicks the link to get the save/open dialogue. Is it possible to just get the save/open dialogue to pop up without them clicking the link? Probably easy but i dont know how to do it? – Barry Jan 10 '14 at 19:52

0 Answers0