txt类文件读写类

1、文本类文件读写方法类 

静态类:txtParser
   public static class txtParser
    {
        public static  List<string> ReadTxt(string strFilePath)
        {
            FileStream fs = new FileStream(strFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            StreamReader sr = new StreamReader(fs, Encoding.UTF8);
            List<string> result  = new List<string>();
            string strLine = "";
            int i = 0;
            while ((strLine = sr.ReadLine()) != null)
            {
                result.Add(strLine);
                i++;
            }
            sr.Close();
            fs.Close();
            sr.Dispose();
            fs.Dispose();
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="strFilePath"></param>
        /// <param name="list"></param>
        public static void WriteTxt(string strFilePath,List<string> list)
        {
            FileStream fs = new FileStream(strFilePath, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
            foreach(var item in list)
            {
                sw.WriteLine(item);
            }          
            sw.Flush();
            sw.Close();
            fs.Close();
            sw.Dispose();
            fs.Dispose();
        }
    }

2、方法调用:

txtParser.WriteTxt(path, jsonList);
        public bool SaveToFile<T>(List<T> Models, string directory, string fileName)
        {

            if (!(Models != null && Models.Count > 0))
                return false;

            try
            {
                List<string> jsonList = new List<string>();
                foreach (var item in Models)
                {
                    string jsonString = JsonConvert.SerializeObject(item);
                    jsonList.Add(jsonString);
                }
                string path = directory + "\\" + DateTime.Now.ToString("yyyy-MM");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                path += "\\" + fileName;
                txtParser.WriteTxt(path, jsonList);
                return true;
            }
            catch (System.Exception ext)
            {
                ShowAction?.Invoke(this.ToString() + "保存Json文件失败:" + ext.Message, true);
                ShowAction?.Invoke(this.ToString() + "保存Json文件失败:" + ext.Message, false);
                return false;
            }
        }

 

posted @ 2022-01-20 15:07  leaon  阅读(54)  评论(0)    收藏  举报