/// <summary> /// 序列化对象成xml文本 /// </summary> /// <param name="obj">待序列化对象</param> /// <param name="encoding">编码方式(默认UTF8)</param> /// <returns></returns> public static string ToXml <T>(T obj, Encoding encoding = null) { EncodingExt.SetEncoding(ref encoding); var serializer = new XmlSerializer(typeof(T)); using (var ms = new MemoryStream()) { var xmlSet = new XmlWriterSettings { Encoding = encoding, Indent = true, IndentChars = " ", NewLineChars = "\r\n", OmitXmlDeclaration = false }; var ns = new XmlSerializerNamespaces(); ns.Add("", ""); using (var xw = XmlWriter.Create(ms, xmlSet)) { serializer.Serialize(xw, obj, ns); } ms.Position = 0; using (var sw = new StreamReader(ms, encoding)) { return(sw.ReadToEnd()); } } }
/// <summary> /// 写入文本。若文件不存在,则先创建 /// <para>IOFilePathException异常</para> /// </summary> /// <param name="path">文件路径</param> /// <param name="text">文本内容</param> /// <param name="isAppend">是否以追加方式写入</param> /// <param name="encoding">编码方式(默认UTF8)</param> public static void Write(string path, string text, bool isAppend = false, Encoding encoding = null) { EncodingExt.SetEncoding(ref encoding); CreateFile(path); // 去只读 RemoveReadonly(path); using (var sw = new StreamWriter(path, isAppend, encoding)) { sw.WriteLine(text); } }
/// <summary> /// 反序列化xml文本至对象 /// </summary> /// <param name="xmlOrPath">待反序列化文本或文件的路径</param> /// <param name="isPath">是否从指定路径加载文件</param> /// <param name="encoding">编码方式(默认UTF8)</param> /// <returns></returns> public static T XmlTo <T>(string xmlOrPath, bool isPath = false, Encoding encoding = null) { EncodingExt.SetEncoding(ref encoding); // 如果是文件路径,则先加载文件 string xml = isPath ? IOExt.ReadXml(xmlOrPath).InnerXml : xmlOrPath; var serializer = new XmlSerializer(typeof(T)); using (var ms = new MemoryStream(encoding.GetBytes(xml))) { using (var sw = new StreamReader(ms, encoding)) { return((T)serializer.Deserialize(sw)); } } }
/// <summary> /// 读取文本 /// <para>IOFilePathException异常</para> /// <para>IOException</para> /// </summary> /// <param name="path">文件路径</param> /// <param name="encoding">编码方式(默认UTF8)</param> /// <returns></returns> public static string Read(string path, Encoding encoding = null) { EncodingExt.SetEncoding(ref encoding); if (!CheckFilePath(path)) { throw new IOFilePathException(path); } if (!File.Exists(path)) { throw new IOException($"文件路径【{path}】不存在!"); } using (var sw = new StreamReader(path, encoding)) { return(sw.ReadToEnd()); } }