Read a file line by line with VB.NET

2019-04-06 02:36发布

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.

...

    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.

2条回答
相关推荐>>
2楼-- · 2019-04-06 03:03

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()
查看更多
疯言疯语
3楼-- · 2019-04-06 03:20

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.

查看更多
登录 后发表回答