ASP:GB2312格式文本文件转换成UTF-8格式

时间:2023-01-06 13:02:32

'-------------------------------------------------
'函数名称:gb2utf_file
'作用:利用AdoDb.Stream对象来把GB2312格式文本文件转换成UTF-8格式
'----------------------------------------------------
Function gb2utf_file(utffilename)
Dim gb2utf_1,gb2utf_2,gb2utf_array,gb2utf_i
gb2utf_1=LoadFile(utffilename,"GB2312")
gb2utf_array=Split(gb2utf_1,Chr(13)&chr(10))
If InStr(Ucase(gb2utf_array(0)),"LANGUAGE=")>0 and InStr(Ucase(gb2utf_array(0)),"CODEPAGE=")>0 and InStr(Ucase(gb2utf_array(0)),"936")>0 Then
gb2utf_array(0)="<%@LANGUAGE=""VBSCRIPT"" CODEPAGE=""65001""%"&">"
End If
For gb2utf_i=0 To UBound(gb2utf_array)
if InStr(Lcase(gb2utf_array(gb2utf_i)),"http-equiv=")>0 and InStr(Lcase(gb2utf_array(gb2utf_i)),"content-type")>0 and InStr(Lcase(gb2utf_array(gb2utf_i)),"content=")>0 and InStr(Lcase(gb2utf_array(gb2utf_i)),"text/html;")>0 and InStr(Lcase(gb2utf_array(gb2utf_i)),"charset=gb2312")>0 Then
gb2utf_array(gb2utf_i)="<meta http-equiv=""Content-Type"" content=""text/html; charset=utf-8"">"
End if
gb2utf_2=gb2utf_2&gb2utf_array(gb2utf_i)&Chr(13)&chr(10)
Next
SaveToFile gb2utf_2,utffilename,"UTF-8"
End Function
'-------------------------------------------------
'函数名称:LoadFile
'作用:利用AdoDb.Stream对象来读取文本文件
'Charset参数为文本格式:UTF-8格式或GB2312格式
'----------------------------------------------------
Function LoadFile(ByVal File,Charset)
       Dim objStream
       On Error Resume Next
       Set objStream = Server.CreateObject("ADODB.Stream")
       If Err.Number=-2147221005 Then
           Response.Write "<div align='center'>非常遗憾,您的主机不支持ADODB.Stream,不能使用本程序</div>"
           Err.Clear
           Response.End
       End If
       With objStream
           .Type = 2
           .Mode = 3
           .Open
           .LoadFromFile Server.MapPath(File)
           If Err.Number<>0 Then
       Response.Write "<div align='center'>文件<font color='#ff0000'>"&File&"</font>无法被打开,请检查是否存在!</font></div>"
       Err.Clear
       Response.End
           End If
           .Charset = Charset
           .Position = 2
           LoadFile = .ReadText
           .Close
       End With
       Set objStream = Nothing
End Function
'-------------------------------------------------
'函数名称:SaveToFile
'作用:利用AdoDb.Stream对象来存储文本文件
'Charset参数为文本格式:UTF-8格式或GB2312格式
'----------------------------------------------------
Sub SaveToFile(ByVal strBody,ByVal File,Charset)
       Dim objStream
       On Error Resume Next
       Set objStream = Server.CreateObject("ADODB.Stream")
       If Err.Number=-2147221005 Then
           Response.Write "<div align='center'>非常遗憾,您的主机不支持ADODB.Stream,不能使用本程序</div>"
           Err.Clear
           Response.End
       End If
       With objStream
           .Type = 2
           .Open
           .Charset = Charset
           .Position = objStream.Size
           .WriteText = strBody
           .SaveToFile Server.MapPath(File),2
           .Close
       End With
       Set objStream = Nothing
End Sub