Click here to Skip to main content
15,884,883 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
i want to read a unicode text file.

code is:
C#
private void button1_Click(object sender, EventArgs e)
       {
           try
           {
               using (StreamReader sr = new StreamReader("F:/car_ads.txt", System.Text.Encoding.Unicode))
               {
                  
                   string line = sr.ReadLine();
                   textBox1.Text = line;
               }
           }
           catch (Exception ex)
           {
               textBox1.Text = "Could not read the file";


           }

       }

when i m running this code ..its giving me .. could not read the file.
plz help me
Posted
Updated 14-May-15 19:42pm
v2
Comments
Mehdi Gholam 15-May-15 2:03am    
Examine the ex for the exception and see what the error is.

1 solution

There is no such encoding, "Unicode". Core part of Unicode standard does not define any computer presentation, but UTFs define some. None of the UTF's are called "Unicode", but this absurd and confusing word in dirty Microsoft jargon means "UTF-16LE". This UTF is not the most used in files, but it corresponds to the UTF for internal representation of strings in memory. For files, UTF-8 is more typical. Very usually, concrete UTF can be determined by BOM. Please see:
http://unicode.org/faq/utf_bom.html[^].

This is the universal code in case BOM is used (absent BOM will be treated as ANSI):
C#
using (StreamReader reader = new StreamReader(fileName, true)) { // true is auto-detection
   string line = reader.ReadLine(); 
   // and so on...
} // here, reader.Dispose is automatically called
Please see: https://msdn.microsoft.com/en-us/library/7bc2hwcb%28v=vs.110%29.aspx[^].

Sometimes, UTF is used without the BOM. In such pathological cases, try out different encodings from this list:
https://msdn.microsoft.com/en-us/library/system.text.encoding%28v=vs.110%29.aspx[^].

What if the encoding is not Unicode one? Then take a guess and try something else. Here is the quick way: rename the file to .HTML, open with the browser and use its auto-detection feature, if you know the language.

—SA
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900