欢迎光临
我们一直在努力

VBnet操作文本文件的问题-.NET教程,VB.Net语言

建站超值云服务器,限时71元/月

.net里面的streamreader读取文本文件默认使用utf-8的编码,因此,如果你写一个最简单的使用streamreader.readtoend的方法读出一个文本文件放入文本框中,八成出现的是乱码。因为在中文系统上,纯文本文件默认的保存编码是ascii。

但是使用的时候也不能全部都按照ascii来读,因为你也无法保证系统上是否会读到unicode的文件。因此,需要一个侦测文件编码类型并且能够按照相应类型来读取的方法。

找了一个小时,终于找到了。

如果文件是有特定编码格式的,这个编码会记录在文件的头四个字节里。因此,读出这四个字节,检查是否是unicode就可以了。如果这四个字节并没有特定的意义,你就只能猜测一个了,一般情况下,就default就比较合适了。

public function loadfile(byval filename as string) as string

dim enc as encoding

dim file as filestream = new filestream(filename, filemode.open, fileaccess.read, fileshare.read)

if file.canseek then

dim bom(3) as byte

file.read(bom, 0, 4)

if ((bom(0) = &hef and bom(1) = &hbb and bom(2) = &hbf) or (bom(0) = &hff and bom(1) = &hfe) or (bom(0) = &hfe and bom(1) = &hff) or (bom(0) = 0 and bom(1) = 0 and bom(2) = &hfe and bom(3) = &hff)) then

enc = encoding.unicode

else

enc = encoding.default

end if

file.seek(0, seekorigin.begin)

else

enc = encoding.default

end if

dim filebyte(file.length) as byte

file.read(filebyte, 0, file.length)

转成系统对应的编码字符

dim myencoder as encoding = enc

file.close()

file = nothing

return new string(myencoder.getchars(filebyte))

end function

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » VBnet操作文本文件的问题-.NET教程,VB.Net语言
分享到: 更多 (0)

相关推荐

  • 暂无文章