/// <summary> /// 将对象反序列化为指定XML文件 /// </summary> /// <param name="filePath">路径</param> /// <param name="sourceObj">对象</param> /// <returns>是否成功</returns> public static bool ObjectToXml(string filePath, object sourceObj) { lock (LockObject) { try { if (!string.IsNullOrWhiteSpace(filePath) && sourceObj != null) { string folderPath = filePath.Substring(0, filePath.LastIndexOf(@"\")); if (Directory.Exists(folderPath) == false) { Directory.CreateDirectory(folderPath); } try { using (StreamWriter writer = new StreamWriter(filePath)) { CreateXMLSerial(sourceObj.GetType()).Serialize(writer, sourceObj); } } catch (Exception ex) { log.Err("将对象反序列化为指定XML文件失败:" + ex.ToString()); return(false); } } else { log.Err("将对象反序列化为指定XML文件失败:路径或对象是否为空"); return(false); } } catch (Exception e) { MessageBox.Show("ObjectToXml 写入XML出错", "Err", MessageBoxButtons.OK, MessageBoxIcon.Error); } } return(true); }
public static bool ObjectToJson(string strFilePath, object obj) { string folderPath = strFilePath.Substring(0, strFilePath.LastIndexOf(@"\")); if (Directory.Exists(folderPath) == false) { Directory.CreateDirectory(folderPath); } try { string strRet = JsonConvert.SerializeObject(obj); using (StreamWriter sw = new StreamWriter(strFilePath, false)) { sw.WriteLine(strRet); } return(true); } catch (Exception exp) { log.Err(obj.GetType().ToString() + "序列化异常" + exp.ToString()); return(false); } }