Operating text files in VB.NET Select Blog from BPFISH

xiaoxiao2021-03-06  108

Several methods such as OpenText and AppenText in .NET in system.io.fileinfo are used using UTF-8 encoding operation files. This causes files that are not written using UTF-8 encoding There will be garbled phenomena!!!

The solution is to use byte stream operations in text files, that is, the use of OpenText and AppenText provided in .NET, the text is used as binary files, and the eNCoding method is used in operation. That is. Implementation code is as follows:

Open the text file:

Public Function LoadFile (Byval FileName As String) AS String

IF filename = "" ""

Return ""

END IF

Try

DIM FileReader as fileStream = file.open (filename, filemode.open)

DIM FileByte (FileReader.length) as Byte

FileReader.read (Filebyte, 0, FileReader.Length)

'Code character corresponding to the system

Dim myencoder as encoding = encoding.default

FileReader.close ()

FileReader = Nothing

Return New String (MyEncoder.getChars (filebyte))

Catch e as exception

Return ""

END TRY

End Sub

save document:

Public Sub Savetofile (ByVal FileName As String)

'/ * Write the contents of the Conten string to the filename file

IF filename = "" ""

EXIT SUB

END IF

Try

Dim filetowrite as filestream = file.create (filename)

Dim rbyte () as byte = encoding.default.getbytes (Conten.ToChararray)

Filetowrite.write (rbyte, 0, rbyte.length)

Filetowrite.close ()

FILETOWRITE = Nothing

Catch e as exception

END TRY

End Sub

Use the above two methods to implement the encoding operation text file corresponding to the current system. Avoid messy issues ....

转载请注明原文地址:https://www.9cbs.com/read-99551.html

New Post(0)