最新发布 C# xml对object存取

发布时间: 2022-12-30,浏览量:379
public class XmlHelper
    {
        private static string xmlpath = @"/Content/webset/";
        private static string xmlname="ini.xml";
        
        public static bool XmlWrite<T>(T obj)
        {
            string path = HttpContext.Current.Server.MapPath(xmlpath + xmlname);
           
            //创建序列化对象 
           
            try
            {
                using (FileStream xmlfile = new FileStream(path, FileMode.Create))
                {
                    XmlSerializer xml = new XmlSerializer(typeof(T));
                    //序列化对象
                    xml.Serialize(xmlfile, obj);
                    xmlfile.Close();
                    //CacheManage.Instance.Remove("SiteMsg_catch");
                    return true;
                }
               
                
            }
            catch (InvalidOperationException)
            {
                throw;
            }
           
 
            
          
        }
        public static T XmlRead<T>()
        {
            string path = HttpContext.Current.Server.MapPath(xmlpath + xmlname);
            
            XmlSerializer xml = new XmlSerializer(typeof(T));      
            try
            {
                using (FileStream xmlfile = new FileStream(path, FileMode.Open))
                {
                    T t = (T)xml.Deserialize(xmlfile);
                    return t;
                }
            }
            catch (InvalidOperationException)
            {
                throw;
            }
            catch (FileNotFoundException)
            { throw; }
            finally
            {
              
            }
 
        }
 
 
    }

热门文章 经典语录

热门文章 热门文章

查看更多