VBnet操作文本文件的問題
2024-07-21 02:20:55
供稿:網友
.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