【问题标题】:.NET Console.WriteLine() Console.SetOut.NET Console.WriteLine() Console.SetOut
【发布时间】:2016-07-23 04:09:25
【问题描述】:

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

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

【问题讨论】:

    标签: .net vb.net console.writeline console.setout


    【解决方案1】:

    然后您将标准输出流设置为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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-01
      • 1970-01-01
      • 2011-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-29
      • 2011-04-29
      相关资源
      最近更新 更多