I have written a program to go through a fixed file and insert a | where needed, The program works fine and displays in the console correctly. The issue is I cannot get the line from the console to write to a line in the file. All attempts end up with an empty file or with each string of a line written as an individual line. The code below shows the one where it should write the output to a file but the file is blank.
Imports System.IO
Module Module1
Sub Main()
Dim stdFormat As Integer() = {3, 13, 11, 5, 2, 2, 13, 14, 30, 15, 76, 80, 95, 100, 50, 2, 10, 30}
Using MyReader As New FileIO.TextFieldParser("SOURCE.txt")
MyReader.TextFieldType = FileIO.FieldType.FixedWidth
MyReader.FieldWidths = stdFormat
Dim currentRow As String()
While Not MyReader.EndOfData
Try
Dim rowType = MyReader.PeekChars(3)
If String.Compare(rowType, "Err") = 0 Then
Else
MyReader.SetFieldWidths(stdFormat)
End If
currentRow = MyReader.ReadFields
For Each newString In currentRow
Console.Write(newString & "|")
Next
Dim file = New FileStream("test.txt", FileMode.Append)
Dim standardOutput = Console.Out
Using writer = New StreamWriter(file)
Console.SetOut(writer)
Console.WriteLine()
Console.SetOut(standardOutput)
End Using
Catch ex As FileIO.MalformedLineException
End Try
End While
End Using
Console.ReadLine()
End Sub
End Module
You are then setting the standard out stream to
writer
, writing a single newline to the standard out (redirected towriter
), then resetting the standard out stream.What you need to do is write to the file. Don't mess around with redirecting the streams. If we combine both the console and file writing, we can make this a bit cleaner.