VB 判断是否文本文件

这段代码展示了如何使用VB来判断一个文件是否为文本文件。通过检查字节序列和字符编码,函数IsTextFile能识别ASCII、UTF-8和GBK编码的文本文件。
摘要由CSDN通过智能技术生成

 代码如下:

Option Explicit

Public Function IsTextFile(Bytes() As Byte) As Boolean
Dim i As Long, AscN As Long, Length As Long
Length = UBound(Bytes) + 1

If Length < 3 Then
IsTextFile = IsGB(Bytes, Length)
Exit Function
ElseIf Bytes(0) = &HEF And Bytes(1) = &HBB And Bytes(2) = &HBF Then
IsTextFile = True
Exit Function
End If

Do While i <= Length - 1
If Bytes(i) < 128 Then
i = i + 1
AscN = AscN + 1
ElseIf (Bytes(i) And &HE0) = &HC0 And (Bytes(i + 1) And &HC0) = &H80 Then
i = i + 2

ElseIf i + 2 < Length Then
If (Bytes(i) And &HF0) = &HE0 And (Bytes(i + 1) And &HC0) = &H80 And (Bytes(i + 2) And &HC0) = &H80 Then
i = i + 3
Else
IsTextFile = IsGB(Bytes, Length)
Exit Function
End If
Else
IsTextFile = IsGB(Bytes, Length)
Exit Function
End If
Loop

If AscN = Length Then
IsTextFile = IsGB(Bytes, Length)
Else
IsTextFile = True
End If

End Function

Private Function IsGB(Bytes() As Byte, FileSize As Long) As Boolean
Dim ObjStream As Object, ret As String
Set ObjStream = CreateObject("ADODB.Stream")
With ObjStream
.Type = 1
.Mode = 3
.open
.Write Bytes
.Position = 0
.Type = 2
.Charset = "GB2312"
ret = .ReadText
.Close
End With
If LenB(StrConv(ret, vbFromUnicode)) = FileSize Then
IsGB = True
Else
IsGB = False
End If
End Function

摘自:网络整理


相关参考


VB输入文本文件实现右对齐

VB计算文本文件的行数

VB打开文本文件各种方法

vb:读写文本文件

vb UTF文本文件访问

简述UTF8编码原理及其文本文件的读写技术【转】

VB 读写TXT文本文件函数

VB 判断是否文本文件

VB 按指定编码格式写入文本文件

 
 

VB相关

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值