VB.Net - Writing to ASCII files

Here is a command to append to a text file.

1
2
3
Using sw As System.IO.StreamWriter = System.IO.File.AppendText(CSVFileName)
sw.WriteLine( message )
End Using

You need to initialize the CSVFileName variable with a filename, and the Message variable with what you want to put into that file.

DatasetToText

Here is an example of some code to export a dataset to an ascii file on the client PC

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Private Sub ExportToText(ByVal ds As DataSet, ByVal response As HttpResponse)

'create a string writer
Dim stringWrite As New System.IO.StringWriter

'create an htmltextwriter which uses the stringwriter
'Dim htmlWrite As New System.Web.UI.HtmlTextWriter(stringWrite)
For Each row As DataRow In ds.Tables(0).Rows
Dim Barcodeid As String = row.Item("barcode_id")
Dim device_type As String = row.Item("device_type")
Dim device As String = row.Item("device")
Dim insp_last_date As String = row.Item("insp_last_dte")
Dim inspection As String = row.Item("inspection")
stringWrite.WriteLine(Barcodeid & ControlChars.Tab & device_type & ControlChars.Tab & device & ControlChars.Tab & insp_last_date & ControlChars.Tab & inspection)
Next

'first let's clean up the response.object

response.Clear()
response.Charset = ""
response.ContentType = "text/csv"
response.AddHeader("Content-Disposition", "attachment;filename=S01_data.txt")

'all that's left is to output the html
response.Write(stringWrite.ToString)
response.End()
End Sub

Reading an ascii file

Here is an example of reading an ascii file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Dim sr As System.IO.StreamReader
Try
sr = New System.IO.StreamReader(FileName)
Catch ex As Exception
Return "Did not find " & FileName
End Try

l = sr.ReadLine
l = sr.ReadLine

' row 3 on to the rest of the file is done
' in a loop. This would be common if the file
' you are reading isn't exactly a formatted file

Dim theLine As String = ""
Do While Not sr.EndOfStream
theLine = sr.ReadLine
'
' additional logic added here
'
loop
sr.Close()

Note: In ASP.Net the filename is respective to where that particular code is being executed from. For example c:\test.txt - might cause this program to check the server’s root. Later versions of IIS will restrict where this code can access.