【问题标题】:Is it possible to load a .config file from a string of XML in memory without writing to file?是否可以从内存中的 XML 字符串加载 .config 文件而不写入文件?
【发布时间】:2009-06-04 21:49:49
【问题描述】:

我知道如何使用ConfigurationFileMap 类和ConfigurationManager.OpenMappedMachineConfiguration 从文件中加载Configuration 对象,但是有没有办法只从纯XML 中加载Configuration 对象?

【问题讨论】:

    标签: .net configuration


    【解决方案1】:

    是的。这个帮助类应该允许您从 xml 读取或写入任何对象,包括您的 ConfigurationManager 对象。

    public static class XmlUtility
    {
        /// <summary>
        /// Serializes an object to an XML string.
        /// </summary>
        public static string ToXML(object Obj)
        {
            Type T = Obj.GetType();
            XmlSerializer xs = new XmlSerializer(T);
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                xs.Serialize(ms, Obj);
                UTF8Encoding ue = new UTF8Encoding();
                return ue.GetString(ms.ToArray());
            }
        }
    
        /// <summary>
        /// Deserializes an object from an XML string.
        /// </summary>
        public static T FromXML<T>(string xml)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            using (StringReader sr = new StringReader(xml))
            {
                return (T)xs.Deserialize(sr);
            }
        }
    }
    

    【讨论】:

    • 问题是 - 你不能反序列化任何与配置相关的对象 - 试过了,但失败了。它们包含反序列化失败的东西(成员变量和其他东西)......这通常有效,但在这种特殊情况下,它不会工作:-(
    猜你喜欢
    • 2011-02-21
    • 2010-10-31
    • 2011-01-11
    • 2018-10-31
    • 2016-02-19
    • 1970-01-01
    • 2020-01-07
    • 1970-01-01
    • 2020-01-10
    相关资源
    最近更新 更多