在.net里的system.io.file和system.io.fileinfo里的opentext和appentext等幾個方法都是使用utf-8編碼操作文件的.這就導(dǎo)致如果操作不是使用utf-8編碼編寫的文件時將會出現(xiàn)亂碼現(xiàn)象!!! 解決方法就是對文本文件使用字節(jié)流操作,即不使用.net里提供的opentext和appentext等幾個方法,而是將文本當(dāng)成二進制文件來操作,并且在操作時使用encoding的方法進行相應(yīng)的解碼即可.實現(xiàn)代碼如下: 打開文本文件: public function loadfile(byval filename as string) as string if filename= "" then return "" end if try dim filereader as filestream = file.open(filename, filemode.open) dim filebyte(filereader.length) as byte filereader.read(filebyte, 0, filereader.length) '轉(zhuǎn)成系統(tǒng)對應(yīng)的編碼字符 dim myencoder as encoding = encoding.default filereader.close() filereader = nothing return new string(myencoder.getchars(filebyte)) catch e as exception return "" end try end sub
保存文件: public sub savetofile(byref conten as string, byval filename as string) '/*將conten字符串的內(nèi)容寫入filename文件 if filename = "" then exit sub end if try dim filetowrite as filestream = file.create(filename) dim rbyte() as byte = encoding.default.getbytes(conten.tochararray) filetowrite.write(rbyte, 0, rbyte.length) filetowrite.close() filetowrite = nothing catch e as exception end try end sub