为什么 VBS 不能正确读取此文本文件? [英] Why does VBS not read this text file correctly?

查看:35
本文介绍了为什么 VBS 不能正确读取此文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码来读取文本文件:

选项显式昏暗的输入文件昏暗的 FSO,oFile模糊字符串数据InputFile = "C:\Program Files (x86)\AVG\CloudCare\ClientVersion.txt"Set FSO = CreateObject("Scripting.FileSystemObject")设置 oFile = FSO.OpenTextFile(InputFile)strData = oFile.ReadAlloFile.Closemsgbox 字符串数据

ClientVersion.txt 的内容为:

CLIENT_VERSION_STRING _T("3.5.2")//

当我运行 VBS 代码时,我得到这个:

如果我在同一位置创建一个具有相同内容的新文本文件,它工作正常.VBS 无法读取这个简单的文本文件有什么原因吗?我看不到文件权限有任何问题.

解决方案

ÿþUTF-16 Little Endian 编码文件的">字节顺序标记.UTF-16(与 ASCII/ANSI 不同)为一个字符使用两个字节而不是一个字节.但是,OpenTextFile 方法默认将文件读取为 ASCII 文件,因此每个 2 字节字符被解释为两个单独的字符.

来自文档:

<块引用>

语法

object.OpenTextFile(filename[, iomode[, create[, format]]])

参数
[…]
格式
    可选.用于指示打开文件格式的三个 Tristate 值之一(TristateTrue = -1 以 Unicode 格式打开文件,TristateFalse= 0 以 ASCII 格式打开文件,TristateUseDefault = -2 以系统默认格式打开文件).如果省略,文件将以 ASCII 格式打开.

读取文件时指定正确的编码,问题就会消失:

Set oFile = FSO.OpenTextFile(InputFile, 1, False, -1)

I have the following code to read a text file:

Option Explicit 
Dim InputFile 
Dim FSO, oFile 
Dim strData 

InputFile = "C:\Program Files (x86)\AVG\CloudCare\ClientVersion.txt" 
Set FSO = CreateObject("Scripting.FileSystemObject") 
Set oFile = FSO.OpenTextFile(InputFile) 
strData = oFile.ReadAll 
oFile.Close 
msgbox strData 

The contents of ClientVersion.txt is:

CLIENT_VERSION_STRING   _T("3.5.2") //

When I run the VBS code, I get back this:

If I create a new text file with the same content in the same location, it works fine. Is there a reason why VBS is unable to read this simple text file? I couldn't see any issues with permissions on the file.

解决方案

ÿþ is the byte order mark of a UTF-16 Little Endian encoded file. UTF-16 (unlike ASCII/ANSI) uses two bytes for a character instead of just one. However, the OpenTextFile method reads files as ASCII files by default, so each 2-byte character gets interpreted as two separate characters.

From the documentation:

Syntax

object.OpenTextFile(filename[, iomode[, create[, format]]])

Arguments
[…]
format
    Optional. One of three Tristate values used to indicate the format of the opened file (TristateTrue = -1 to open the file as Unicode, TristateFalse = 0 to open the file as ASCII, TristateUseDefault = -2 to open the file as the system default). If omitted, the file is opened as ASCII.

Specify the proper encoding when reading the file and the problem will disappear:

Set oFile = FSO.OpenTextFile(InputFile, 1, False, -1)

这篇关于为什么 VBS 不能正确读取此文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆