How to get a text file's encoding name by analyzing its byte in order to dynamically interpret it according to its Character encoding

Viewed 39
   public string[] AbrirArquivo(byte[] Arquivo)
        {
            
            var arquivoTxt = new StreamReader(new MemoryStream(Arquivo), Encoding.GetEncoding("utf-8")).ReadToEnd();

            var linhas = arquivoTxt.Split('\n');

            return linhas;
        }

I want to create a variable before the var arquivoTxt and store inside it, the value of Arquivo's Character encoding. So I will replace the "utf-8" to my new variable, and then through this manner, my work will be completed. The issue is, I don't know how to get the value of Arquivo's Character encoding. Could any body help me out to solve this, please?.

Because many of the users aren't English speakers, The problem often is because many of them upload ANSI encoded files, then the special Characters get broken, and it sucks. I really need to find out a way to figure this out.

1 Answers

Thank you guys very much, I did solve it!! Now it doesn't matter if they will unpload ANSI or UTF-8, it always gonna work.

` public string[] AbrirArquivo(byte[] Arquivo)
    {
        Boolean podeSerUtf8 = ValidaCodificacaoUTF8Arquivo(Arquivo);

        String codificacao = podeSerUtf8 ? "utf-8" : "Windows-1252";

        var arquivoTxt = new StreamReader(new MemoryStream(Arquivo), Encoding.GetEncoding(codificacao)).ReadToEnd();
        var linhas = arquivoTxt.Split('\n');

        return linhas;
    }

    public Boolean ValidaCodificacaoUTF8Arquivo(byte[] Arquivo)
    {
     
        String text = null;
        UTF8Encoding encUtf8Bom = new UTF8Encoding(true, true);
        Boolean podeSerUtf8 = true;
        Byte[] preamble = encUtf8Bom.GetPreamble();
        Int32 prLen = preamble.Length;

        if (Arquivo.Length >= prLen && preamble.SequenceEqual(Arquivo.Take(prLen)))
        {
            try
            {
                text = encUtf8Bom.GetString(Arquivo, prLen, Arquivo.Length - prLen);
            }
            catch (Exception)
            {
                podeSerUtf8 = false;
            }
        }


        if (podeSerUtf8)
        {
            UTF8Encoding encUtf8NoBom = new UTF8Encoding(false, true);

            try
            {
                text = encUtf8NoBom.GetString(Arquivo);
            }
            catch (Exception)
            {
                podeSerUtf8 = false;
            }
        }

        return podeSerUtf8;
    }`
Related