Skip to content Skip to sidebar Skip to footer

Writing Utf8 Text To File

I am using the following function to save text to a file (on IE-8 w/ActiveX). function saveFile(strFullPath, strContent) { var fso = new ActiveXObject( 'Scripting.FileSystemObj

Solution 1:

Try this:

functionsaveFile(strFullPath, strContent) {
 var fso = newActiveXObject("Scripting.FileSystemObject");
 var utf8Enc = newActiveXObject("Utf8Lib.Utf8Enc");
 var flOutput = fso.CreateTextFile(strFullPath, true); //true for overwrite
 flOutput.BinaryWrite(utf8Enc.UnicodeToUtf8(strContent));
 flOutput.Close();
}

Solution 2:

The CreateTextFile method has a third parameter which decides whether file be written unicode or not. You can do like:

var flOutput = fso.CreateTextFile(strFullPath,true, true);

Interestingly, way back I had created this little script to save files in unicode format:

Set FSO=CreateObject("Scripting.FileSystemObject")
Value = InputBox ("Enter the path of the file you want to save in Unicode format.")

If Len(Trim(Value)) > 0ThenIf FSO.FileExists(Value) ThenSet iFile = FSO.OpenTextFile (Value)
        Data = iFile.ReadAll
        iFile.Close

        Set oFile = FSO.CreateTextFile (FSO.GetParentFolderName(Value) & "\Unicode" & GetExtention(Value),True,True)
        oFile.Write Data
        oFile.Close

        If FSO.FileExists (FSO.GetParentFolderName(Value) & "\Unicode" & GetExtention(Value)) Then
            MsgBox "File successfully saved to:" & vbCrLf & vbCrLf &  FSO.GetParentFolderName(Value) & "\Unicode" & GetExtention(Value),vbInformation
        Else
            MsgBox "Unknown error was encountered!",vbCritical
        EndIfElse
        MsgBox "Make sure that you have entered the correct file path.",vbExclamation
    EndIfEndIfSet iFile = NothingSet oFile= NothingSet FSO= NothingFunction GetExtention (Path)
    GetExtention = Right(Path,4)
EndFunction

Note: This is VBScript code, you should save that code in a file like unicode.vbs, and once you double click that file, it will run.

Solution 3:

Add a third parameter, true, in your call to the CreateTextFile method. See this page.

Solution 4:

functionsaveFile(strFullPath, strContent) {
    var fso = newActiveXObject( "Scripting.FileSystemObject" );
    var flOutput = fso.CreateTextFile( strFullPath, true, true ); //true for overwrite // true for unicode
    flOutput.Write( strContent );
    flOutput.Close();
}

object.CreateTextFile(filename[, overwrite[, unicode]])

Post a Comment for "Writing Utf8 Text To File"