.NET Console.WriteLine()Console.SetOut

.NET Console.WriteLine()Console.SetOut,.net,vb.net,console.writeline,console.setout,.net,Vb.net,Console.writeline,Console.setout,我已经编写了一个程序来遍历一个固定的文件,并在需要的地方插入一个|,该程序运行良好,并在控制台中正确显示。问题是我无法从控制台获取该行以写入文件中的行。 所有尝试都以一个空文件或一行中的每个字符串作为单独的行结束。下面的代码显示了它应该将输出写入文件但文件为空的代码 Imports System.IO Module Module1 Sub Main() Dim stdFormat As Integer() = {3, 13, 11, 5, 2, 2, 13, 14, 3

我已经编写了一个程序来遍历一个固定的文件,并在需要的地方插入一个|,该程序运行良好,并在控制台中正确显示。问题是我无法从控制台获取该行以写入文件中的行。 所有尝试都以一个空文件或一行中的每个字符串作为单独的行结束。下面的代码显示了它应该将输出写入文件但文件为空的代码

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

然后将标准输出流设置为
writer
,向标准输出写入一个换行符(重定向到
writer
),然后重置标准输出流

您需要做的是写入文件。不要乱动重定向流。如果我们将控制台和文件写入结合起来,我们可以使它更干净一些

Using writer = New StreamWriter(file)
    String newStr = ""
    For Each columnStr In currentRow
        newStr = columnStr & "|"
        writer.WriteLine(newStr)
        // If you don't want the console output, just remove the next line
        Console.WriteLine(newStr)
    Next
End Using