vb.net 用VB.NET逐行读取文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16921080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 16:56:13  来源:igfitidea点击:

Read a file line by line with VB.NET

vb.netfileutf-8

提问by user2452250

The following code is used to read a file line by line.

以下代码用于逐行读取文件。

It's just a very early version, so all I want to do is display the string in the immediate window. It's working fine, except that characters such as ? ü ? è à and so on are replaced by a black square with a question mark. According to the documentation, the file reader should be compatible with UTF-8 chars so I don't know what is wrong.

这只是一个非常早期的版本,所以我想做的就是在即时窗口中显示字符串。它工作正常,除了诸如 ? ü ? è à 等被替换为带问号的黑色方块。根据文档,文件阅读器应该与 UTF-8 字符兼容,所以我不知道出了什么问题。

...

    Dim reader = File.OpenText(filetoimport.Text)

    Dim line As String = Nothing

    Dim lines As Integer = 0

    While (reader.Peek() <> -1)
        line = reader.ReadLine()
        If line.StartsWith("<item key=""") Then
            Dim Firstpart As String = Nothing

            Firstpart = line.Substring(11, line.IndexOf(""" value=") - 11)

            Debug.WriteLine(Firstpart)

            lines = lines + 1

            Label3.Text = lines
            Application.DoEvents()
        Else
            Label3.Text = lines
            Application.DoEvents()
        End If

    End While

...

The file is ANSI-encoded, not UTF-8, but the reader uses UTF-8.

该文件是 ANSI 编码的,而不是 UTF-8,但阅读器使用的是 UTF-8。

采纳答案by user2452250

Replaced the reader declaration with this one and now it works!

用这个替换了读者声明,现在它可以工作了!

Dim reader As New StreamReader(filetoimport.Text, Encoding.Default)

Encoding.Default represents the ANSI code page that is set under Windows Control Panel.

Encoding.Default 表示在 Windows 控制面板下设置的 ANSI 代码页。

回答by matzone

Like this... I used it to read Chinese characters...

像这样……我用它来读汉字……

Dim reader as StreamReader = My.Computer.FileSystem.OpenTextFileReader(filetoimport.Text)
Dim a as String

Do
   a = reader.ReadLine
   '
   ' Code here
   '
Loop Until a Is Nothing

reader.Close()