Is encoding not an enumeration?

I am trying to figure out a way to store the encoding of a file in a database, then get it back to its original type (System.Text.Encoding). But I get an error that I do not understand.

As a test, I created this small program to reproduce the error:

using System;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            object o = Encoding.Unicode;
            Encoding enc = (Encoding) Enum.Parse(typeof(Encoding), o.ToString());
        }
    }
}

The exception that I get in the Parse line says:

Type provided must be an Enum.
Parameter name: enumType

So basically, as I understand it, they tell me that the typeof(Encoding)type is not Enum? Thanks in advance for the help provided.

+5
source share
4 answers

No, this is not a rename. This is a class with static properties. Something like that:

public class Encoding
{
    public static Encoding ASCII
    {
         get
         {
             //This is purely illustrative. It is not actually implemented like this
             return new ASCIIEncoding();
         }
    }
}

If you want to save the encoding in the database, save the code page:

int codePage = SomeEncoding.CodePage;

Encoding.GetEncoding(theCodePage), .

+12

. , , , :

public abstract class Encoding : ICloneable
+2

Encoding - , . Encoding.Unicode . :

Encoding enc = (Encoding) Enum.Parse(typeof(Encoding), o.ToString()); 

Enum.Parse, , enumType, .

+1

Encoding.Unicode Encoding.ASCII readonly Encoding. enum.

CodePage Encoding.GetEncoding:

// store the encoding
WriteToDatabase(myEncoding.CodePage);

// retrieve the encoding used
Encoding encoding = Encoding.GetEncoding(/* value from the database */);

... , .

+1

All Articles