How to change the encoding of a txt file?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • hamidfirooze
    New Member
    • Jan 2011
    • 2

    How to change the encoding of a txt file?

    Hi
    I want to read a txt file and write its contents into a textbox. The problem is that the content of txt file is not in English and I have to change the encoding. So how could I change the encoding to utf-8 in my code?
    Thank you.
  • Samuel Jones
    New Member
    • Jan 2011
    • 48

    #2
    What is the original encoding?

    Comment

    • hamidfirooze
      New Member
      • Jan 2011
      • 2

      #3
      Hi Samuel
      The original encoding is ANSI.
      By the way,I used this code, but it didn't work.

      string s = File.ReadAllTex t("C:\\1.txt" , System.Text.UTF 8Encoding.UTF8) ;
      textBox1.Text = s;

      Comment

      • Samuel Jones
        New Member
        • Jan 2011
        • 48

        #4
        This should do the conversion fine:

        Code:
         //str is the contents of your file.
        Encoding ANSI = Encoding.GetEncoding(1252);
        
        byte[] ansiBytes = ANSI.GetBytes(str);
        byte[] utf8Bytes = Encoding.Convert(ANSI, Encoding.UTF8, ansiBytes);
        
        String utf8String = Encoding.UTF8.GetString(utf8bytes);
        I presume you already know how to read a text file.

        Sam.

        Comment

        Working...