Q:

How to change string encoding after reading it from file using default encoding?

I want to read text file which includes information about its encoding in its content. I don't know what encoding is used before I read the file. I use System.IO.File.ReadAllText for reading the file. How can I convert encoding without reading the file again?
I was trying to specify default encoding while reading the file and then converting it to final encoding, but it doesn't convert correctly:
string input = File.ReadAllText(filePath, Encoding.Default);
Encoding encoding = GetEncodingFromInput(input);
input = encoding.GetString(Encoding.Convert(Encoding.Default, encoding, Encoding.Default.GetBytes(input)));

Converted string doesn't contain the same characters as when it was read with correct encoding. Some characters are changed to question marks.

A:

I don't know what encoding is used before I read the file.

Usually files that self-declare their encoding somehow have a documented technique or method for finding it - check your file format's published documentation.
If not, here's a few common techniques:

Look for a Unicode BOM in the first few bytes. You can do this by first reading the first 5 bytes from the file into a buffer (or 64-bit integer) and looking them up in a dictionary. This is what System.IO.StreamReader does by default.

You can see a list of known BOM byte sequences here: https://en.wikipedia.org/wiki/Byte_order_mark 
Note that UTF-8 does not have a BOM - but many editors (well, just Visual Studio) will stick 0xEF 0xBB 0xBF at the beginning).

If it's a text/*-family of file-formats, with the encoding declared in some kind of header then you can read the first kilobyte of the file into a buffer and interpret every consecutive byte valued under 0x7F as a character in an ASCII string, then use a simple parser (even String.IndexOf) or a Regex to look for your header's delimiter.

This technique is often used for HTML files where the HTTP header declaring the encoding isn't available and the program needs to look for <meta http-equiv="Content-Type" /> to get the encoding name.

I use System.IO.File.ReadAllText for reading the file. How can I convert encoding without reading the file again?

You don't. Only use ReadAllText for simple text/plain files with consistent and known encoding - for this scenario else you'll need to use Stream and StreamReader (and possibly BinaryReader) together.

A:

Use System.IO.File.ReadAllBytes to read the file, and then de-encode the byte array after you know which encoding you need, using something like: System.Text.Encoding.XXXX.GetString()

