using CnasSynchronousCommon; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Xml; using System.Xml.Serialization; namespace CnasSynchronousCommon { public static class FileHelper { /// /// 获取本地文件 /// /// public static string GetLocalFile(string strLocalPath,string strFileName) { string strLocalXML = ""; try { string strUrl = strLocalPath + strFileName; if (File.Exists(strUrl)) { string temp = ""; using (StreamReader sr = new StreamReader(strUrl, Encoding.UTF8)) { while (!sr.EndOfStream)//读到结尾退出 { temp += sr.ReadLine(); } } strLocalXML = temp; } else { AppLog.Error($"没有找到{strFileName}相关数据"); } } catch (Exception ex) { AppLog.Error($"读取文件{strFileName}时发生错误:{ex.Message}"); } return strLocalXML; } /// /// 保存本地文件 /// /// public static bool SaveLocalFile(string strLocalPath,string strFileName, string strData) { bool bIfSuccess = true; try { if (!Directory.Exists(strLocalPath)) { Directory.CreateDirectory(strLocalPath); } string strUrl = strLocalPath + strFileName; FileStream fs = new FileStream(strUrl, FileMode.Create, FileAccess.ReadWrite); StringBuilder sBld = new StringBuilder(); sBld.Append(strData); //byte[] byteFile = Encoding.Default.GetBytes(sBld.ToString()); byte[] byteFile = Encoding.GetEncoding("utf-8").GetBytes(sBld.ToString()); //参数:要写入到文件的数据数组,从数组的第几个开始写,一共写多少个字节 fs.Write(byteFile, 0, byteFile.Length); fs.Close(); fs.Dispose(); } catch (Exception ex) { bIfSuccess = false; AppLog.Error($"保存文件{strFileName}时发生错误:{ex.Message}"); } return bIfSuccess; } /// /// 获取当前dll所在目录 /// /// public static string getBasePath() { //获取当前DLL 所在路径 string dllpath = System.Reflection.Assembly.GetExecutingAssembly().CodeBase; if (dllpath != null && dllpath.Length > 0) dllpath = dllpath.Substring(8) + @"\"; FileInfo tmpDllInfo = new FileInfo(dllpath); dllpath = tmpDllInfo.DirectoryName; dllpath = dllpath.Replace(tmpDllInfo.Directory.Name, ""); return dllpath; } /// /// 将自定义对象序列化为XML字符串 /// /// 自定义对象实体 /// 序列化后的XML字符串 public static string SerializeToXml(T myObject) { if (myObject != null) { XmlSerializer xs = new XmlSerializer(typeof(T)); MemoryStream stream = new MemoryStream(); XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8); writer.Formatting = Formatting.None;//缩进 xs.Serialize(writer, myObject); stream.Position = 0; StringBuilder sb = new StringBuilder(); using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { string line; while ((line = reader.ReadLine()) != null) { sb.Append(line); } reader.Close(); } writer.Close(); return sb.ToString(); } return string.Empty; } /// /// 将XML字符串反序列化为对象 /// /// 对象类型 /// XML字符 /// public static T DeserializeToObject(string xml) { T myObject; XmlSerializer serializer = new XmlSerializer(typeof(T)); StringReader reader = new StringReader(xml); myObject = (T) serializer.Deserialize(reader); reader.Close(); return myObject; } } }