ASP自动检测判断文本文件编码格式

ASP在读取或存储文件时老是乱码,原来是没有用正确的编码格式打开,解决方案是先取得文件编码,stream流再按照正确的编码打开,就不会乱码了。

原理:用stream对象预读文件的头两个字节,分析判断出utf-8,unicode,ANSI(简体中文操作系统,即gb2312)编码。

ANSI:        无格式定义; Unicode:     前两个字节为FFFE; Unicode big endian:  前两字节为FEFF;  UTF-8:       前两字节为EFBB;
代码如下:
function checkcode(path)
set objstream=server.createobject("adodb.stream")
objstream.Type=1
objstream.mode=3
objstream.open
objstream.Position=0
objstream.loadfromfile path
bintou=objstream.read(2)
If AscB(MidB(bintou,1,1))=&HEF And AscB(MidB(bintou,2,1))=&HBB Then
checkcoder="utf-8"
ElseIf AscB(MidB(bintou,1,1))=&HFF And AscB(MidB(bintou,2,1))=&HFE Then
checkcode="unicode"
Else
checkcode="gb2312"
End If
objstream.close
set objstream=nothing
end function

补充:

ANSI的本地编码,都是各国自己定义的,没有固定的文件头格式,在大陆中文操作系统下,是可读的gb2312,在其他语言的系统下,就是乱码,所以这部分没必要再详细区分

也可以用FSO对文件读写

 FSO.CreateTextFile(filename[, overwrite[, unicode]])
- 2 ' 以系统默认格式打开文件。 - 1 ' 以 Unicode 格式打开文件。 0 ' 以 ASCII 格式打开文件。
两上用读写文件的代码:

' -------------------------------------------------
' 函数名称:ReadTextFile
' 作用:利用AdoDb.Stream对象来读取UTF-8格式的文本文件
' ----------------------------------------------------
 Function  ReadFromTextFile (FileUrl,CharSet)
     dim  str
     set  stm = server.CreateObject( " adodb.stream " )
    stm.Type = 2   ' 以本模式读取
     stm.mode = 3  
    stm.charset = CharSet
    stm.open
    stm.loadfromfile server.MapPath(FileUrl)
    str = stm.readtext
    stm.Close
     set  stm = nothing
    ReadFromTextFile = str
 End Function
————————————————
版权声明:本文为CSDN博主「火舞天涯007」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/cjy37/article/details/1657784
' -------------------------------------------------
' 函数名称:WriteToTextFile
' 作用:利用AdoDb.Stream对象来写入UTF-8格式的文本文件
' ----------------------------------------------------
 Sub  WriteToTextFile (FileUrl,byval Str,CharSet) 
     set  stm = server.CreateObject( " adodb.stream " )
    stm.Type = 2   ' 以本模式读取
     stm.mode = 3
    stm.charset = CharSet
    stm.open
    stm.WriteText str
    stm.SaveToFile server.MapPath(FileUrl), 2  
    stm.flush
    stm.Close
     set  stm = nothing
 End Sub
————————————————
版权声明:本文为CSDN博主「火舞天涯007」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/cjy37/article/details/1657784