Exemplo n.º 1
0
        public static async Task <EncodingInformation> DetectEncodingAsync(Stream stream)
        {
            var cdet = new CharsetDetector();

            await cdet.FeedAsync(stream).ConfigureAwait(false);

            cdet.DataEnd();

            if (cdet.Charset != null)
            {
                if (Encodings.TryGetValue(cdet.Charset, out var encoding))
                {
                    return(new EncodingInformation
                    {
                        Encoding = encoding,
                        BomDetected = cdet.BomDetected
                    });
                }

                try
                {
                    return(new EncodingInformation
                    {
                        Encoding = Encoding.GetEncoding(cdet.Charset),
                        BomDetected = cdet.BomDetected
                    });
                }
                catch (ArgumentException ex)
                {
                    Debug.WriteLine("Encoding {0} not found: {1}", cdet.Charset, ex.Message);
                }

                Console.WriteLine("Unknown encoding for " + cdet.Charset);
            }
            else
            {
                Console.WriteLine("Detection failed.");
            }

            return(null);
        }