ExcelHome技术论坛

 找回密码
 免费注册

QQ登录

只需一步,快速开始

快捷登录

搜索
EH技术汇-专业的职场技能充电站 妙哉!函数段子手趣味讲函数 Excel服务器-会Excel,做管理系统 效率神器,一键搞定繁琐工作
HR薪酬管理数字化实战 Excel 2021函数公式学习大典 Excel数据透视表实战秘技 打造核心竞争力的职场宝典
让更多数据处理,一键完成 数据工作者的案头书 免费直播课集锦 ExcelHome出品 - VBA代码宝免费下载
用ChatGPT与VBA一键搞定Excel WPS表格从入门到精通 Excel VBA经典代码实践指南
查看: 371|回复: 7

[求助] 请教,vb.net读文本文件ANSI编码,读过后文本文件就乱码

[复制链接]

TA的精华主题

TA的得分主题

发表于 2023-2-19 21:35 | 显示全部楼层 |阅读模式
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用  · 内置多项VBA编程加强工具       ★ 免费下载 ★      ★使用手册
请教,vb.net中,读文本文件(ANSI编码),读过后文本文件就乱码,有没有办法解决,急等.......


补充内容 (2023-2-24 18:48):
以下代码由VBS转成VB.NET,VBS下是可以成功运行的。VB.NET中还有问题,不能正常运行,有懂的高手,帮修改一下,谢谢。'用法:将要更改编码的所有文件放到同一个文件夹中,将文件夹拖到该vbs上,输入要转换成的字...

TA的精华主题

TA的得分主题

 楼主| 发表于 2023-2-19 21:47 | 显示全部楼层
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用  · 内置多项VBA编程加强工具       ★ 免费下载 ★      ★使用手册
好像vb.net不支持ANSI编码

TA的精华主题

TA的得分主题

发表于 2023-2-23 08:46 | 显示全部楼层
至少把你的示例文本文件和你用的代码发出来啊_(:з」∠)_

TA的精华主题

TA的得分主题

 楼主| 发表于 2023-2-23 20:58 | 显示全部楼层
临沂-枸杞 发表于 2023-2-23 08:46
至少把你的示例文本文件和你用的代码发出来啊_(:з」∠)_

    Public Sub ReadFileToArray(ByVal fileName As String, ByRef LineArr As String(), ByRef arr As String())
        arr = File.ReadAllLines(fileName, Encoding.Default)
        Dim str As String = String.Join(",", arr)
        LineArr = str.Split(",")
    End Sub

TA的精华主题

TA的得分主题

 楼主| 发表于 2023-2-23 21:01 | 显示全部楼层
    Public Sub ReadFileToArray(ByVal fileName As String, ByRef LineArr As String(), ByRef arr As String())


        arr = File.ReadAllLines(fileName, Encoding.Default)

        Dim str As String = String.Join(",", arr)
        LineArr = str.Split(",")

    End Sub

TA的精华主题

TA的得分主题

 楼主| 发表于 2023-2-24 18:49 | 显示全部楼层
本帖最后由 prcstone 于 2023-2-24 18:51 编辑


'用法:将要更改编码的所有文件放到同一个文件夹中,将文件夹拖到该vbs上,输入要转换成的字符编码
    Dim fso,fd,fl,f,fdpath,charset
    On Error Resume Next
    If WScript.Arguments.Length>=1 Then
        fdpath = WScript.Arguments(0)
    Else
        fdpath = InputBox("E:\xunlian\新增加的训练集\博彩","第一个参数")
        If fdpath = "" Then WScript.Quit
    End If
    If WScript.Arguments.Length>=2 Then
        charset = WScript.Arguments(1)
    Else
        charset = InputBox("UTF-8","第二个参数")
        if charset = "" then WScript.Quit
        if UCase(charset) = "ANSI" then charset = "GB2312"
    End If
    Set fso = CreateObject("scripting.filesystemobject")
    Set fd = fso.GetFolder(fdpath)
    Set fl=fd.Files
    For each f in fl
        convertct f.Path,charset
    Next
    MsgBox "字符编码转换结束",,"tya提示"
  
'将读取的文件内容以指定编码写入文件
Function convertct(filepath,charset)
    Dim FileName, FileContents, dFileContents
    FileName = filepath
    FileContents = LoadFile(FileName)
    Set savefile = CreateObject("adodb.stream")
    savefile.Type = 2  '这里1为二进制,2为文本型
    savefile.Mode = 3
    savefile.Open()
    savefile.charset = charset
    savefile.Position = savefile.Size
    savefile.Writetext(FileContents)  'write写二进制,writetext写文本型
    savefile.SaveToFile filepath,2
    savefile.Close()
    set savefile = nothing
End Function

'以文件本身编码读取文件
Function LoadFile(Path)
    Dim Stm2
    Set Stm2 = CreateObject("ADODB.Stream")
    Stm2.Type = 2
    Stm2.Mode = 3
    Stm2.Open
    Stm2.Charset = CheckCode(path)
    'Stm2.Charset = "UTF-8"
    'Stm2.Charset = "Unicode"
    'Stm2.Charset = "GB2312"
    Stm2.position = Stm2.Size
    Stm2.LoadFromFile Path
    LoadFile = Stm2.ReadText
    Stm2.Close
    Set Stm2 = Nothing
End Function

'该函数检查并返回文件的编码类型
Function CheckCode(file)
    Dim slz
    set slz = CreateObject("Adodb.Stream")
    slz.Type = 1
    slz.Mode = 3
    slz.Open
    slz.Position = 0
    slz.Loadfromfile file
    Bin=slz.read(2)
    If is_valid_utf8(read(file)) Then
        Codes="UTF-8"
    ElseIf AscB(MidB(Bin,1,1))=&HFF and AscB(MidB(Bin,2,1))=&HFE Then
        Codes="Unicode"
    Else
        Codes="GB2312"
    End if
    slz.Close
    Set slz = Nothing
    CheckCode = Codes
End Function

'将Byte()数组转成String字符串
Function read(path)
    Dim ado, a(), i, n
    Set ado = CreateObject("ADODB.Stream")
    ado.Type = 1 : ado.Open
    ado.LoadFromFile path
    n = ado.Size - 1
    ReDim a(n)
    For i = 0 To n
        a(i) = ChrW(AscB(ado.Read(1)))
    Next
    read = Join(a, "")
End Function

'准确验证文件是否为utf-8(能验证无BOM头的uft-8文件)
Function is_valid_utf8(ByRef input) 'ByRef以提高效率
    Dim s, re
    Set re = New Regexp
    s = "[\xC0-\xDF]([^\x80-\xBF]|$)"
    s = s & "|[\xE0-\xEF].{0,1}([^\x80-\xBF]|$)"
    s = s & "|[\xF0-\xF7].{0,2}([^\x80-\xBF]|$)"
    s = s & "|[\xF8-\xFB].{0,3}([^\x80-\xBF]|$)"
    s = s & "|[\xFC-\xFD].{0,4}([^\x80-\xBF]|$)"
    s = s & "|[\xFE-\xFE].{0,5}([^\x80-\xBF]|$)"
    s = s & "|[\x00-\x7F][\x80-\xBF]"
    s = s & "|[\xC0-\xDF].[\x80-\xBF]"
    s = s & "|[\xE0-\xEF]..[\x80-\xBF]"
    s = s & "|[\xF0-\xF7]...[\x80-\xBF]"
    s = s & "|[\xF8-\xFB]....[\x80-\xBF]"
    s = s & "|[\xFC-\xFD].....[\x80-\xBF]"
    s = s & "|[\xFE-\xFE]......[\x80-\xBF]"
    s = s & "|^[\x80-\xBF]"
    re.Pattern = s
    is_valid_utf8 = (Not re.Test(input))
End Function

TA的精华主题

TA的得分主题

 楼主| 发表于 2023-2-24 18:51 | 显示全部楼层
'用法:将要更改编码的所有文件放到同一个文件夹中,将文件夹拖到该vbs上,输入要转换成的字符编码
    Dim fso,fd,fl,f,fdpath,charset
    On Error Resume Next
    If WScript.Arguments.Length>=1 Then
        fdpath = WScript.Arguments(0)
    Else
        fdpath = InputBox("E:\xunlian\新增加的训练集\博彩","第一个参数")
        If fdpath = "" Then WScript.Quit
    End If
    If WScript.Arguments.Length>=2 Then
        charset = WScript.Arguments(1)
    Else
        charset = InputBox("UTF-8","第二个参数")
        if charset = "" then WScript.Quit
        if UCase(charset) = "ANSI" then charset = "GB2312"
    End If
    Set fso = CreateObject("scripting.filesystemobject")
    Set fd = fso.GetFolder(fdpath)
    Set fl=fd.Files
    For each f in fl
        convertct f.Path,charset
    Next
    MsgBox "字符编码转换结束",,"tya提示"
  
'将读取的文件内容以指定编码写入文件
Function convertct(filepath,charset)
    Dim FileName, FileContents, dFileContents
    FileName = filepath
    FileContents = LoadFile(FileName)
    Set savefile = CreateObject("adodb.stream")
    savefile.Type = 2  '这里1为二进制,2为文本型
    savefile.Mode = 3
    savefile.Open()
    savefile.charset = charset
    savefile.Position = savefile.Size
    savefile.Writetext(FileContents)  'write写二进制,writetext写文本型
    savefile.SaveToFile filepath,2
    savefile.Close()
    set savefile = nothing
End Function

'以文件本身编码读取文件
Function LoadFile(Path)
    Dim Stm2
    Set Stm2 = CreateObject("ADODB.Stream")
    Stm2.Type = 2
    Stm2.Mode = 3
    Stm2.Open
    Stm2.Charset = CheckCode(path)
    'Stm2.Charset = "UTF-8"
    'Stm2.Charset = "Unicode"
    'Stm2.Charset = "GB2312"
    Stm2.position = Stm2.Size
    Stm2.LoadFromFile Path
    LoadFile = Stm2.ReadText
    Stm2.Close
    Set Stm2 = Nothing
End Function

'该函数检查并返回文件的编码类型
Function CheckCode(file)
    Dim slz
    set slz = CreateObject("Adodb.Stream")
    slz.Type = 1
    slz.Mode = 3
    slz.Open
    slz.Position = 0
    slz.Loadfromfile file
    Bin=slz.read(2)
    If is_valid_utf8(read(file)) Then
        Codes="UTF-8"
    ElseIf AscB(MidB(Bin,1,1))=&HFF and AscB(MidB(Bin,2,1))=&HFE Then
        Codes="Unicode"
    Else
        Codes="GB2312"
    End if
    slz.Close
    Set slz = Nothing
    CheckCode = Codes
End Function

'将Byte()数组转成String字符串
Function read(path)
    Dim ado, a(), i, n
    Set ado = CreateObject("ADODB.Stream")
    ado.Type = 1 : ado.Open
    ado.LoadFromFile path
    n = ado.Size - 1
    ReDim a(n)
    For i = 0 To n
        a(i) = ChrW(AscB(ado.Read(1)))
    Next
    read = Join(a, "")
End Function

'准确验证文件是否为utf-8(能验证无BOM头的uft-8文件)
Function is_valid_utf8(ByRef input) 'ByRef以提高效率
    Dim s, re
    Set re = New Regexp
    s = "[\xC0-\xDF]([^\x80-\xBF]|$)"
    s = s & "|[\xE0-\xEF].{0,1}([^\x80-\xBF]|$)"
    s = s & "|[\xF0-\xF7].{0,2}([^\x80-\xBF]|$)"
    s = s & "|[\xF8-\xFB].{0,3}([^\x80-\xBF]|$)"
    s = s & "|[\xFC-\xFD].{0,4}([^\x80-\xBF]|$)"
    s = s & "|[\xFE-\xFE].{0,5}([^\x80-\xBF]|$)"
    s = s & "|[\x00-\x7F][\x80-\xBF]"
    s = s & "|[\xC0-\xDF].[\x80-\xBF]"
    s = s & "|[\xE0-\xEF]..[\x80-\xBF]"
    s = s & "|[\xF0-\xF7]...[\x80-\xBF]"
    s = s & "|[\xF8-\xFB]....[\x80-\xBF]"
    s = s & "|[\xFC-\xFD].....[\x80-\xBF]"
    s = s & "|[\xFE-\xFE]......[\x80-\xBF]"
    s = s & "|^[\x80-\xBF]"
    re.Pattern = s
    is_valid_utf8 = (Not re.Test(input))
End Function

TA的精华主题

TA的得分主题

发表于 2023-4-17 23:01 | 显示全部楼层
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件       ★免费下载 ★       ★ 使用帮助
  1. #Region "读取文件流"
  2.     ''' <summary>
  3.     ''' 读取文件流
  4.     ''' </summary>
  5.     ''' <param name="path">文件地址</param>
  6.     ''' <returns>返回Byte文件流</returns>
  7.     <Runtime.CompilerServices.Extension>
  8.     Public Function ReadFile(path As String) As String
  9.         Using FileStream As New FileStream(path, FileMode.Open, FileAccess.Read)
  10.             Try
  11.                 With FileStream
  12.                     Dim Buffur(.Length - 1) As Byte
  13.                     .Read(Buffur, 0, .Length)
  14.                     .Seek(0, SeekOrigin.Begin)
  15.                     Return Buffur.BytesFormatText
  16.                 End With
  17.             Catch ex As IOException
  18.                 Throw New IOException(ex.Message)
  19.                 Return Nothing
  20.             End Try
  21.         End Using
  22.     End Function
  23. #End Region
  24. #Region "写入文件流"
  25.     ''' <summary>
  26.     ''' 写入文件流
  27.     ''' </summary>
  28.     ''' <param name="content"></param>
  29.     ''' <param name="path"></param>
  30.     ''' <returns>是否成功</returns>
  31.     Public Function WriterFile(content As String, path As String, Optional Append As Boolean = False) As Boolean
  32.         If String.IsNullOrEmpty(content) Then Return False
  33.         Dim Buffur() As Byte = Encoding.Default.GetBytes(content)
  34.         Using FileStream As New FileStream(path, FileMode.Create)
  35.             Try
  36.                 With FileStream
  37.                     If Append = True Then .Position = .Length
  38.                     .Write(Buffur, 0, Buffur.Length)
  39.                     .Close()
  40.                 End With
  41.                 Return True
  42.             Catch ex As IOException
  43.                 Throw New IOException(ex.Message)
  44.                 Return False
  45.             End Try
  46.         End Using
  47.     End Function
  48.     ''' <summary>
  49.     ''' 写入文件流
  50.     ''' </summary>
  51.     ''' <param name="sb"></param>
  52.     ''' <param name="path"></param>
  53.     ''' <returns></returns>
  54.     Public Function WriterFile(sb As StringBuilder, path As String, Optional Append As Boolean = False) As Boolean
  55.         Return sb IsNot Nothing AndAlso Not String.IsNullOrEmpty(sb.ToString) AndAlso WriterFile(sb.ToString, path, Append)
  56.     End Function
  57.     ''' <summary>
  58.     ''' 写入文件流
  59.     ''' </summary>
  60.     ''' <param name="array"></param>
  61.     ''' <param name="path"></param>
  62.     ''' <param name="Append"></param>
  63.     ''' <returns></returns>
  64.     Public Function WriterFile(array As IEnumerable(Of String), path As String, Optional Append As Boolean = False) As Boolean
  65.         Return array IsNot Nothing AndAlso WriterFile(String.Join(vbTab, array), path, Append)
  66.     End Function
  67. #End Region
复制代码
您需要登录后才可以回帖 登录 | 免费注册

本版积分规则

手机版|关于我们|联系我们|ExcelHome

GMT+8, 2024-11-21 22:31 , Processed in 0.032183 second(s), 8 queries , Gzip On, MemCache On.

Powered by Discuz! X3.4

© 1999-2023 Wooffice Inc.

沪公网安备 31011702000001号 沪ICP备11019229号-2

本论坛言论纯属发表者个人意见,任何违反国家相关法律的言论,本站将协助国家相关部门追究发言者责任!     本站特聘法律顾问:李志群律师

快速回复 返回顶部 返回列表