Difference between revisions of "Encoding"

From Xojo Documentation

 
Line 60: Line 60:
  
 
Catch error As NilObjectException
 
Catch error As NilObjectException
   MessageDialog.Show(error.Message)
+
   MessageBox(error.Message)
 
End Try
 
End Try
 
</rbcode>
 
</rbcode>

Latest revision as of 02:14, 30 August 2019

Method

Returns the text encoding of the passed String.

Syntax

result=sourceVariable.Encoding

Part Type Description
result TextEncoding The text encoding of str.
sourceVariable String The string whose TextEncoding will be returned.

Notes

This method does not attempt to "guess" the encoding of a String. It only returns the encoding of a String as it is known. Strings have a UTF-8 encoding by default. If you load data of another encoding into a String (from a file, perhaps), you will need to specify the encoding using DefineEncoding.

If the string's encoding is unknown, Encoding returns Nil. Test whether the TextEncoding object is Nil or include an Exception block if there is a chance the string's encoding would not be known at runtime.

Examples

Var f As FolderItem
Var t As TextInputStream
Var source As String
Var enc As TextEncoding
f = GetOpenFolderItem("text") // file type defined via the FileType class
If f <> Nil Then
t = TextInputStream.Open(f)
source = t.ReadAll
t.Close
End If

Try
enc = source.Encoding // This will be Encodings.UTF8

// If the file actually has text in a different encoding, then specify the
// encoding using DefineEncoding
source = source.DefineEncoding(Encodings.UTF16LE)

enc = source.Encoding // This is now Encodings.UTF16LE

Catch error As NilObjectException
MessageBox(error.Message)
End Try

See Also

TextConverter, TextEncoding, TextInputStream classes; String.ConvertEncoding, String.DefineEncoding, GetTextEncoding functions; Encodings module.