序列化FileSystemWatcher对象

时间:2013-08-05 09:06:12

标签: c# serialization filesystemwatcher

我想将FileSystemWatcher对象存储在sqlite数据库中以供将来参考,但在序列化对象时获得以下异常

“在程序集'系统中键入'System.IO.FileSystemWatcher',版本= 2.0.0.0,文化=中立,PublicKeyToken = b77a5c561934e089'未标记为可序列化。”

这是代码

            MemoryStream memorystream = new MemoryStream();
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(memorystream, FSWatcher);
            byte[] yourBytesToDb = memorystream.ToArray();

谢谢和问候, Haseena

1 个答案:

答案 0 :(得分:0)

使用XML

public static void SaveAsXML(Object A, string FileName)
{
    var serializer = new XmlSerializer(A.GetType());
    using (var textWriter = new StreamWriter(FileName))
    {
        serializer.Serialize(textWriter, A);
        textWriter.Close();
    }
}

public static T LoadFromXML<T>(string FileName) where T : class
{
    if (File.Exists(FileName))
    {
        using (var textReader = new StreamReader(FileName))
        {
            var deserializer = new XmlSerializer(typeof(T));
            return (T)(deserializer.Deserialize(textReader));
        }
    }
    return default(T);
}