Geeks With Blogs
Fórmulas e Cenas Object Reference Not Set to an Instance of an Object

As found in: http://www.personalmicrocosms.com/Pages/dotnettips.aspx?c=15&t=17

 

public static Encoding GetFileEncoding(String FileName)
{
            Encoding Result = null;
            FileInfo FI = new FileInfo(FileName);
            FileStream FS = null;

            try
            {
                FS = FI.OpenRead();
                Encoding[] UnicodeEncodings = { Encoding.BigEndianUnicode, Encoding.Unicode, Encoding.UTF8 };
                for(int i = 0; Result == null && i < UnicodeEncodings.Length; i++)
                {
                    FS.Position = 0;
                    byte[] Preamble = UnicodeEncodings[i].GetPreamble();
                    bool PreamblesAreEqual = true;
                    for(int j = 0; PreamblesAreEqual && j < Preamble.Length; j++)
                    {
                        PreamblesAreEqual = Preamble[j] == FS.ReadByte();
                    }
                    if(PreamblesAreEqual)
                    {
                        Result = UnicodeEncodings[i];
                    }
                }
            }
            catch(System.IO.IOException)
            {
            }
            finally
            {
                if(FS != null)
                {
                    FS.Close();
                }
            }

            if(Result == null)
            {
                Result = Encoding.Default;
            }

            return Result;
        }

 

To use this:

 

 Encoding encode = GetFileEncoding(@"C:\myFile.txt");
 StreamReader re = new StreamReader(@"C:\myFile.txt", encode);

 

 

Enjoy :)

Posted on Tuesday, December 15, 2009 5:41 AM C# | Back to top


Comments on this post: How to: Open text file using the correct file encoding

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Sglima | Powered by: GeeksWithBlogs.net