According to several answers here on SO, eg. How can I detect the encoding/codepage of a text file it is not possible to retrieve the encoding of a file.
How does VS do it then? If I "Save as", and select "Save with encoding" it shows the current encoding of my file.
By default, the editor detects encoding by searching for byte order marks or charset tags. If neither is found in the current document, the code editor attempts to auto-detect UTF-8 encoding by scanning byte sequences. VS Help
If VS fails to convert any byte sequences to valid unicode symbols, it opens file in default system character set. No magic realy.