用VB.NET逐行读取文件 [英] Read a file line by line with VB.NET

查看:459
本文介绍了用VB.NET逐行读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这只是一个非常早期的版本,所以我要做的就是在立即窗口中显示字符串.效果很好,只是将ÄÜÖèà等字符替换为带有问号的黑色正方形.根据文档,文件阅读器应该与UTF-8字符兼容,所以我不知道这是怎么回事.

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

...

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

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

推荐答案

将阅读器声明替换为现在的声明!

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

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

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

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

这篇关于用VB.NET逐行读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆