Eljay
Elite Member
:O
Posts: 2949 Reputation: 77
– / / –
Joined: May 2004
|
RE: unicode problem
As usual, I am going to take Matty's code apart and optimize it!
code: /*----------
Title: _ReadFile
Description: Read the contents of a file, whether it is Unicode or ASCII.
Author: Eljay <leejeffery@gmail.com>
----------*/
function _ReadFile(Path){
var Handle = Interop.Call("kernel32", "CreateFileW", Path, 0x80000000, 1, 0, 3, 0, 0);
if(Handle == -1) return; //If file doesn't exist, just exit function.
var FileSize = Interop.Call("kernel32", "GetFileSize", Handle, 0);
var Buffer = Interop.Allocate(FileSize + 1);
var BytesRead = Interop.Allocate(4);
Interop.Call("kernel32", "ReadFile", Handle, Buffer, FileSize, BytesRead, 0);
var IsUnicode = Interop.Call("advapi32", "IsTextUnicode", Buffer, FileSize, 0);
Interop.Call("kernel32", "CloseHandle", Handle);
if(IsUnicode) return Buffer.ReadString(2, true, (FileSize / 2) - 1);
else return Buffer.ReadString(0, false, FileSize);
}
Changes:
+Uses IsTextUnicode API to perform more accurate tests for file encoding.
+Changed file buffer size, it doesnt need to be twice the file size for unicode as the size is in bytes not characters.
+No need for everything to be inside if block if you don't do anything with else.
+Removed first 2 bytes from Unicode files (this doesn't contain file data, just encoding information).
+Read whole file, not just up to first null byte (third parameter of ReadString).
|
|