Lire en anglais

Partager via


SerializationException Classe

Définition

Exception levée quand une erreur se produit pendant la sérialisation ou la désérialisation.

C#
public class SerializationException : Exception
C#
public class SerializationException : SystemException
C#
[System.Serializable]
public class SerializationException : SystemException
C#
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class SerializationException : SystemException
Héritage
SerializationException
Héritage
SerializationException
Attributs

Exemples

C#
// Note: You must compile this file using the C# /unsafe switch.
using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;

// This class includes several Win32 interop definitions.
internal class Win32
{
    public static readonly IntPtr InvalidHandleValue = new IntPtr(-1);
    public const UInt32 FILE_MAP_WRITE = 2;
    public const UInt32 PAGE_READWRITE = 0x04;

    [DllImport("Kernel32",CharSet=CharSet.Unicode)]
    public static extern IntPtr CreateFileMapping(IntPtr hFile,
        IntPtr pAttributes, UInt32 flProtect,
        UInt32 dwMaximumSizeHigh, UInt32 dwMaximumSizeLow, String pName);

    [DllImport("Kernel32",CharSet=CharSet.Unicode)]
    public static extern IntPtr OpenFileMapping(UInt32 dwDesiredAccess,
        Boolean bInheritHandle, String name);

    [DllImport("Kernel32",CharSet=CharSet.Unicode)]
    public static extern Boolean CloseHandle(IntPtr handle);

    [DllImport("Kernel32",CharSet=CharSet.Unicode)]
    public static extern IntPtr MapViewOfFile(IntPtr hFileMappingObject,
        UInt32 dwDesiredAccess,
        UInt32 dwFileOffsetHigh, UInt32 dwFileOffsetLow,
        IntPtr dwNumberOfBytesToMap);

    [DllImport("Kernel32",CharSet=CharSet.Unicode)]
    public static extern Boolean UnmapViewOfFile(IntPtr address);

    [DllImport("Kernel32",CharSet=CharSet.Unicode)]
    public static extern Boolean DuplicateHandle(IntPtr hSourceProcessHandle,
        IntPtr hSourceHandle,
        IntPtr hTargetProcessHandle, ref IntPtr lpTargetHandle,
        UInt32 dwDesiredAccess, Boolean bInheritHandle, UInt32 dwOptions);
    public const UInt32 DUPLICATE_CLOSE_SOURCE = 0x00000001;
    public const UInt32 DUPLICATE_SAME_ACCESS = 0x00000002;

    [DllImport("Kernel32",CharSet=CharSet.Unicode)]
    public static extern IntPtr GetCurrentProcess();
}

// This class wraps memory that can be simultaneously
// shared by multiple AppDomains and Processes.
[Serializable]
public sealed class SharedMemory : ISerializable, IDisposable
{
    // The handle and string that identify
    // the Windows file-mapping object.
    private IntPtr m_hFileMap = IntPtr.Zero;
    private String m_name;

    // The address of the memory-mapped file-mapping object.
    private IntPtr m_address;

    public unsafe Byte* Address
    {
        get { return (Byte*)m_address; }
    }

    // The constructors.
    public SharedMemory(Int32 size) : this(size, null) { }

    public SharedMemory(Int32 size, String name)
    {
        m_hFileMap = Win32.CreateFileMapping(Win32.InvalidHandleValue,
            IntPtr.Zero, Win32.PAGE_READWRITE,
            0, unchecked((UInt32)size), name);
        if (m_hFileMap == IntPtr.Zero)
            throw new Exception("Could not create memory-mapped file.");
        m_name = name;
        m_address = Win32.MapViewOfFile(m_hFileMap, Win32.FILE_MAP_WRITE,
            0, 0, IntPtr.Zero);
    }

    // The cleanup methods.
    public void Dispose()
    {
        GC.SuppressFinalize(this);
        Dispose(disposing: true);
    }

    private void Dispose(Boolean disposing)
    {
        Win32.UnmapViewOfFile(m_address);
        Win32.CloseHandle(m_hFileMap);
        m_address = IntPtr.Zero;
        m_hFileMap = IntPtr.Zero;
    }

    ~SharedMemory()
    {
        Dispose(disposing: false);
    }

    // Private helper methods.
    private static Boolean AllFlagsSet(Int32 flags, Int32 flagsToTest)
    {
        return (flags & flagsToTest) == flagsToTest;
    }

    private static Boolean AnyFlagsSet(Int32 flags, Int32 flagsToTest)
    {
        return (flags & flagsToTest) != 0;
    }

    void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
    {
        // The context's State member indicates
        // where the object will be deserialized.

        // A SharedMemory object cannot be serialized
        // to any of the following destinations.
        const StreamingContextStates InvalidDestinations =
                  StreamingContextStates.CrossMachine |
                  StreamingContextStates.File |
                  StreamingContextStates.Other |
                  StreamingContextStates.Persistence |
                  StreamingContextStates.Remoting;
        if (AnyFlagsSet((Int32)context.State, (Int32)InvalidDestinations))
            throw new SerializationException("The SharedMemory object " +
                "cannot be serialized to any of the following streaming contexts: " +
                InvalidDestinations);

        const StreamingContextStates DeserializableByHandle =
                  StreamingContextStates.Clone |
            // The same process.
                  StreamingContextStates.CrossAppDomain;
        if (AnyFlagsSet((Int32)context.State, (Int32)DeserializableByHandle))
            info.AddValue("hFileMap", m_hFileMap);

        const StreamingContextStates DeserializableByName =
            // The same computer.
                  StreamingContextStates.CrossProcess;
        if (AnyFlagsSet((Int32)context.State, (Int32)DeserializableByName))
        {
            if (m_name == null)
                throw new SerializationException("The SharedMemory object " +
                    "cannot be serialized CrossProcess because it was not constructed " +
                    "with a String name.");
            info.AddValue("name", m_name);
        }
    }

    private SharedMemory(SerializationInfo info, StreamingContext context)
    {
        // The context's State member indicates
        // where the object was serialized from.

        const StreamingContextStates InvalidSources =
                  StreamingContextStates.CrossMachine |
                  StreamingContextStates.File |
                  StreamingContextStates.Other |
                  StreamingContextStates.Persistence |
                  StreamingContextStates.Remoting;
        if (AnyFlagsSet((Int32)context.State, (Int32)InvalidSources))
            throw new SerializationException("The SharedMemory object " +
                "cannot be deserialized from any of the following stream contexts: " +
                InvalidSources);

        const StreamingContextStates SerializedByHandle =
                  StreamingContextStates.Clone |
            // The same process.
                  StreamingContextStates.CrossAppDomain;
        if (AnyFlagsSet((Int32)context.State, (Int32)SerializedByHandle))
        {
            try
            {
                Win32.DuplicateHandle(Win32.GetCurrentProcess(),
                    (IntPtr)info.GetValue("hFileMap", typeof(IntPtr)),
                    Win32.GetCurrentProcess(), ref m_hFileMap, 0, false,
                    Win32.DUPLICATE_SAME_ACCESS);
            }
            catch (SerializationException)
            {
                throw new SerializationException("A SharedMemory was not serialized " +
                    "using any of the following streaming contexts: " +
                    SerializedByHandle);
            }
        }

        const StreamingContextStates SerializedByName =
            // The same computer.
                  StreamingContextStates.CrossProcess;
        if (AnyFlagsSet((Int32)context.State, (Int32)SerializedByName))
        {
            try
            {
                m_name = info.GetString("name");
            }
            catch (SerializationException)
            {
                throw new SerializationException("A SharedMemory object was not " +
                    "serialized using any of the following streaming contexts: " +
                    SerializedByName);
            }
            m_hFileMap = Win32.OpenFileMapping(Win32.FILE_MAP_WRITE, false, m_name);
        }
        if (m_hFileMap != IntPtr.Zero)
        {
            m_address = Win32.MapViewOfFile(m_hFileMap, Win32.FILE_MAP_WRITE,
                0, 0, IntPtr.Zero);
        }
        else
        {
            throw new SerializationException("A SharedMemory object could not " +
                "be deserialized.");
        }
    }
}

class App
{
    [STAThread]
    static void Main(string[] args)
    {
        Serialize();
        Console.WriteLine();
        Deserialize();
    }

    unsafe static void Serialize()
    {
        // Create a hashtable of values that will eventually be serialized.
        SharedMemory sm = new SharedMemory(1024, "JeffMemory");
        for (Int32 x = 0; x < 100; x++)
            *(sm.Address + x) = (Byte)x;

        Byte[] b = new Byte[10];
        for (Int32 x = 0; x < b.Length; x++) b[x] = *(sm.Address + x);
        Console.WriteLine(BitConverter.ToString(b));

        // To serialize the SharedMemory object,
        // you must first open a stream for writing.
        // Use a file stream here.
        FileStream fs = new FileStream("DataFile.dat", FileMode.Create);

        // Construct a BinaryFormatter and tell it where
        // the objects will be serialized to.
        BinaryFormatter formatter = new BinaryFormatter(null,
            new StreamingContext(StreamingContextStates.CrossAppDomain));
        try
        {
            formatter.Serialize(fs, sm);
        }
        catch (SerializationException e)
        {
            Console.WriteLine("Failed to serialize. Reason: " + e.Message);
            throw;
        }
        finally
        {
            fs.Close();
        }
    }

    unsafe static void Deserialize()
    {
        // Declare a SharedMemory reference.
        SharedMemory sm = null;

        // Open the file containing the data that you want to deserialize.
        FileStream fs = new FileStream("DataFile.dat", FileMode.Open);
        try
        {
            BinaryFormatter formatter = new BinaryFormatter(null,
                new StreamingContext(StreamingContextStates.CrossAppDomain));

            // Deserialize the SharedMemory object from the file and
            // assign the reference to the local variable.
            sm = (SharedMemory)formatter.Deserialize(fs);
        }
        catch (SerializationException e)
        {
            Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
            throw;
        }
        finally
        {
            fs.Close();
        }

        // To prove that the SharedMemory object deserialized correctly,
        // display some of its bytes to the console.
        Byte[] b = new Byte[10];
        for (Int32 x = 0; x < b.Length; x++) b[x] = *(sm.Address + x);
        Console.WriteLine(BitConverter.ToString(b));
    }
}

Remarques

SerializationException utilise le HRESULT COR_E_SERIALIZATION avec la valeur 0x8013150C.

SerializationException utilise l’implémentation par défaut Equals , qui prend en charge l’égalité des références.

Pour obtenir la liste des valeurs initiales des propriétés d’une instance de SerializationException, consultez le SerializationException constructeurs.

Constructeurs

SerializationException()

Initialise une nouvelle instance de la classe SerializationException avec des propriétés par défaut.

SerializationException(SerializationInfo, StreamingContext)

Initialise une nouvelle instance de la classe SerializationException à partir de données sérialisées.

SerializationException(String)

Initialise une nouvelle instance de la classe SerializationException avec le message spécifié.

SerializationException(String, Exception)

Initialise une nouvelle instance de la classe SerializationException avec un message d'erreur spécifié et une référence à l'exception interne ayant provoqué cette exception.

Propriétés

Data

Obtient une collection de paires clé/valeur qui fournissent des informations définies par l'utilisateur supplémentaires sur l'exception.

(Hérité de Exception)
HelpLink

Obtient ou définit un lien vers le fichier d'aide associé à cette exception.

(Hérité de Exception)
HResult

Obtient ou définit HRESULT, valeur numérique codée qui est assignée à une exception spécifique.

(Hérité de Exception)
InnerException

Obtient l'instance Exception qui a provoqué l'exception actuelle.

(Hérité de Exception)
Message

Obtient un message qui décrit l'exception active.

(Hérité de Exception)
Source

Obtient ou définit le nom de l'application ou de l'objet qui est à l'origine de l'erreur.

(Hérité de Exception)
StackTrace

Obtient une représentation sous forme de chaîne des frames immédiats sur la pile des appels.

(Hérité de Exception)
TargetSite

Obtient la méthode qui lève l'exception actuelle.

(Hérité de Exception)

Méthodes

Equals(Object)

Détermine si l'objet spécifié est égal à l'objet actuel.

(Hérité de Object)
GetBaseException()

En cas de substitution dans une classe dérivée, retourne la Exception qui est à l'origine d'une ou de plusieurs exceptions ultérieures.

(Hérité de Exception)
GetHashCode()

Fait office de fonction de hachage par défaut.

(Hérité de Object)
GetObjectData(SerializationInfo, StreamingContext)

En cas de substitution dans une classe dérivée, définit SerializationInfo avec des informations sur l'exception.

(Hérité de Exception)
GetType()

Obtient le type au moment de l'exécution de l'instance actuelle.

(Hérité de Exception)
MemberwiseClone()

Crée une copie superficielle du Object actuel.

(Hérité de Object)
ToString()

Crée et retourne une chaîne représentant l'exception actuelle.

(Hérité de Exception)

Événements

SerializeObjectState
Obsolète.

Se produit quand une exception est sérialisée pour créer un objet d'état d'exception qui contient des données sérialisées concernant l'exception.

(Hérité de Exception)

S’applique à

Produit Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 2.0, 2.1
UWP 10.0

Voir aussi