VB6/VBScript change file encoding to ansi

前端 未结 4 877
囚心锁ツ
囚心锁ツ 2020-11-30 12:45

I am looking for a way to convert a textfile with UTF8 encoding to ANSI encoding.

How can i go around and achieve this in Visual Basic (VB6) and or vbscript?

4条回答
  •  独厮守ぢ
    2020-11-30 13:07

    I'm using these helper functions

    Private Function pvReadFile(sFile)
        Const ForReading = 1
        Dim sPrefix
    
        With CreateObject("Scripting.FileSystemObject")
            sPrefix = .OpenTextFile(sFile, ForReading, False, False).Read(3)
        End With
        If Left(sPrefix, 3) <> Chr(&HEF) & Chr(&HBB) & Chr(&HBF) Then
            With CreateObject("Scripting.FileSystemObject")
                pvReadFile = .OpenTextFile(sFile, ForReading, False, Left(sPrefix, 2) = Chr(&HFF) & Chr(&HFE)).ReadAll()
            End With
        Else
            With CreateObject("ADODB.Stream")
                .Open
                If Left(sPrefix, 2) = Chr(&HFF) & Chr(&HFE) Then
                    .Charset = "Unicode"
                ElseIf Left(sPrefix, 3) = Chr(&HEF) & Chr(&HBB) & Chr(&HBF) Then
                    .Charset = "UTF-8"
                Else
                    .Charset = "_autodetect"
                End If
                .LoadFromFile sFile
                pvReadFile = .ReadText
            End With
        End If
    End Function
    
    Private Function pvWriteFile(sFile, sText, lType)
        Const adSaveCreateOverWrite = 2
    
        With CreateObject("ADODB.Stream")
            .Open
            If lType = 2 Then
                .Charset = "Unicode"
            ElseIf lType = 3 Then
                .Charset = "UTF-8"
            Else
                .Charset = "_autodetect"
            End If
            .WriteText sText
            .SaveToFile sFile, adSaveCreateOverWrite
        End With
    End Function
    

    I found out that "native" FileSystemObject reading of ANSI and UTF-16/UCS-2 files is much faster that ADODB.Stream hack.

提交回复
热议问题