国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > .NET > 正文

VBnet操作文本文件的問題

2024-07-21 02:20:55
字體:
供稿:網(wǎng)友


.net里面的streamreader讀取文本文件默認(rèn)使用utf-8的編碼,因此,如果你寫一個最簡單的使用streamreader.readtoend的方法讀出一個文本文件放入文本框中,八成出現(xiàn)的是亂碼。因為在中文系統(tǒng)上,純文本文件默認(rèn)的保存編碼是ascii。
但是使用的時候也不能全部都按照ascii來讀,因為你也無法保證系統(tǒng)上是否會讀到unicode的文件。因此,需要一個偵測文件編碼類型并且能夠按照相應(yīng)類型來讀取的方法。
找了一個小時,終于找到了。
如果文件是有特定編碼格式的,這個編碼會記錄在文件的頭四個字節(jié)里。因此,讀出這四個字節(jié),檢查是否是unicode就可以了。如果這四個字節(jié)并沒有特定的意義,你就只能猜測一個了,一般情況下,就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)
'轉(zhuǎn)成系統(tǒng)對應(yīng)的編碼字符
dim myencoder as encoding = enc
file.close()
file = nothing
return new string(myencoder.getchars(filebyte))
end function

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 宁明县| 泊头市| 巫山县| 屏东市| 通江县| 迭部县| 九寨沟县| 凤山县| 阜南县| 平山县| 日土县| 临猗县| 青田县| 安龙县| 崇左市| 吉木萨尔县| 土默特左旗| 贵阳市| 横峰县| 上饶县| 衡水市| 漾濞| 蕉岭县| 于都县| 宁武县| 滁州市| 哈巴河县| 蒲江县| 涟源市| 华亭县| 阳泉市| 宁蒗| 辉县市| 准格尔旗| 濉溪县| 汾西县| 城口县| 钦州市| 正宁县| 循化| 哈巴河县|