简体   繁体   中英

Load text from ANSI encrypted file into a RichTextBox

I am a beginner programmer and I am currently looking for a way to load texts from an ANSI encrypted file to a RichTextBox in my form. Also, I am looking for a way to save it back to the file with ANSI encryption.

This is what am I am currently trying:

Imports System
Imports System.IO
Imports System.Text

Dim strResult As String
Using SR As StreamReader = New StreamReader("startup_config.cfg", Encoding.Default)
    strResult = SR.ReadToEnd
End Using

I believe you mean ANSI encoding instead of encrypted .

You can use Encoding.GetEncoding with one of the code pages from the list here instead of using Encoding.Default . Here's the code sample from the GetEncoding page I linked above:

Imports System
Imports System.Text
Imports Microsoft.VisualBasic

Namespace Convert_Example
  Class MyConvertExampleClass
    Shared Sub Main()
      Dim unicodeString As String = "This string contains the unicode character Pi(" & ChrW(&H03A0) & ")"

      ' Create two different encodings.
      Dim ascii As Encoding = Encoding.ASCII
      Dim [unicode] As Encoding = Encoding.Unicode

      ' Convert the string into a byte[].
      Dim unicodeBytes As Byte() = [unicode].GetBytes(unicodeString)

      ' Perform the conversion from one encoding to the other.
      Dim asciiBytes As Byte() = Encoding.Convert([unicode], ascii, unicodeBytes)

      ' Convert the new byte[] into a char[] and then into a string.
      ' This is a slightly different approach to converting to illustrate
      ' the use of GetCharCount/GetChars.
      Dim asciiChars(ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)) As Char
      ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0)
      Dim asciiString As New String(asciiChars)

      ' Display the strings created before and after the conversion.
      Console.WriteLine("Original string: {0}", unicodeString)
      Console.WriteLine("Ascii converted string: {0}", asciiString)
    End Sub
  End Class
End Namespace

To see if the code page you want is available, you can use GetEncodings to get a list of them.

ANSI encoding may mean any encoding.

Encoding.Default will return your default Code Page in Windows (it depends on regional settings in Windows, where program runs).

If file is encoded with other Code Page you have to set your StreamReader encoding to that Code Page, like this:

Encoding.GetEncoding(1250);

1250 is Central and East European Latin code page.


Added later:

You asked about saving back in that ANSI format - just use StreamWriter with same encoding as StreamReader .

Few code page examples and more about Code Pages at Wikipedia: link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM