This topic has not yet been rated - Rate this topic

StreamReader.CurrentEncoding Property

Gets the current character encoding that the current StreamReader object is using.

Namespace:  System.IO
Assembly:  mscorlib (in mscorlib.dll)
public virtual Encoding CurrentEncoding { get; }

Property Value

Type: System.Text.Encoding
The current character encoding used by the current reader. The value can be different after the first call to any Read method of StreamReader, since encoding autodetection is not done until the first call to a Read method.

For a list of common I/O tasks, see Common I/O Tasks.

The following code example gets the encoding of the specified StreamReader object.


using System;
using System.IO;
using System.Text;

class Test 
{
	
    public static void Main() 
    {
        string path = @"c:\temp\MyTest.txt";

        try 
        {
            if (File.Exists(path)) 
            {
                File.Delete(path);
            }

            //Use an encoding other than the default (UTF8).
            using (StreamWriter sw = new StreamWriter(path, false, new UnicodeEncoding())) 
            {
                sw.WriteLine("This");
                sw.WriteLine("is some text");
                sw.WriteLine("to test");
                sw.WriteLine("Reading");
            }

            using (StreamReader sr = new StreamReader(path, true)) 
            {
                while (sr.Peek() >= 0) 
                {
                    Console.Write((char)sr.Read());
                }

                //Test for the encoding after reading, or at least
                //after the first read.
                Console.WriteLine("The encoding used was {0}.", sr.CurrentEncoding);
                Console.WriteLine();
            }
        } 
        catch (Exception e) 
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}


.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.