CurrentEncoding Property
Collapse the table of content
Expand the table of content

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";

            if (File.Exists(path)) 

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

            using (StreamReader sr = new StreamReader(path, true)) 
                while (sr.Peek() >= 0) 

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

Universal Windows Platform
Available since 4.5
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1
Return to top
© 2015 Microsoft