1

I have used the code below to write the file.

File.WriteAllText(fileName, data, Encoding.Unicode);

When I read the file using code below because the type of File Encoding is run time specific.

using (StreamReader sR = File.OpenText(fileName))
{
    encoding = sR.CurrentEncoding;
}

I get Encoding.UTF8

I've also used the methods in This Link

Can anyone suggest the working way to find the Encoding?

Thanks

Karthik
  • 31
  • 1
  • 1
  • 7
  • `OpenText` always opens as UTF8. https://learn.microsoft.com/en-us/dotnet/api/system.io.file.opentext?view=netcore-3.1 – Roman Ryzhiy Sep 16 '20 at 08:26
  • 3
    A file is just a sequence of bytes. Some guesses are possible if you're not aware of the encoding (although they are just guesses), but you really should *know and specify* the encoding when attempting to open the file. – Damien_The_Unbeliever Sep 16 '20 at 08:27
  • Use `var reader = new StreamReader(fileName, Encoding.Unicode)` instead of `File.OpenText()` – Matthew Watson Sep 16 '20 at 08:29

1 Answers1

2

File.OpenText:

Opens an existing UTF-8 encoded text file for reading.

So it doesn't guess what encoding the file is encoded in. Even if you used Encoding.Unicode when writing the file, File.OpenText will still read it as UTF-8.

If you want to read the file in Unicode, you can create a StreamReader like this:

using (StreamReader sR = new StreamReader(fileName, Encoding.Unicode)) {
   encoding = sR.CurrentEncoding; // Unicode
   // ...
}

If you don't know the file encoding, then you need to detect the encoding.

Sweeper
  • 213,210
  • 22
  • 193
  • 313