Lua中使用Luacom和ADODB读取文本文件出现错误

我正在构建一个通用函数来读取文本文件,该文件可以是Ascii、UTF-8或UTF-16编码的。(在调用函数时已知编码方式)。文件名可能包含UTF8字符,所以标准的Lua IO函数不是一个解决方案。我对Lua实现(5.3)或环境中可用的二进制模块没有控制权。

我的当前代码是:

require "luacom"
local function readTextFile(sPath, bUnicode, iBits)
    local fso = luacom.CreateObject("Scripting.FileSystemObject")
    if not fso:FileExists(sPath) then return false, "" end --检查文件是否存在

    local so = luacom.CreateObject("ADODB.Stream")
    --so.CharSet默认为Unicode,即utf-16
    --so.Type默认为文本
      so.Mode = 1 --adModeRead

    if not bUnicode then
      so.CharSet = "ascii"
    elseif iBits == 8 then
      so.CharSet = "utf-8"
    end

    so:Open()
    so:LoadFromFile(sPath)
    local contents = so:ReadText()
    so:Close()
    return true, contents
end

--测试Unicode(utf-16)文件

local file = "D:\\OneDrive\\Desktop\\utf16.txt" --文件存在
local booOK, factsetcontents = readTextFile(file, true, 16)

执行时出现错误:COM exception:(d:\my\lua\luacom-master\src\library\tluacom.cpp,382):Operation is not allowed in this context,在第19行 [local stream = so:LoadFromFile(sPath)]处。

我研究过ADO文档,显然我错过了一些眼前的东西!我试图做的事情是不可能实现的吗?

ETA:如果我注释掉so.Mode=1这一行,这个函数可以工作。这很棒,但我不明白为什么,这意味着我可能会无意中犯同样的错误,无论这个错误是什么!

点赞
用户15592404
用户15592404

我不了解AdoDB Stream.Mode,也不知道函数为什么失败。但我认为在Windows上使用ADODB COM对象读取ASCII/UTF8/UNICODE编码的文件非常棘手。

你可以选择:

  • 在二进制模式下使用标准的Lua io.open函数,并手动解码字节内容
  • 使用二进制模块来完成所有的工作
  • 使用Windows的特定Lua实现来原生地读/写这些类型的编码文件,比如LuaRT(https://www.luart.org)
2021-05-18 20:51:04