C# 读写文本文件

//读取文件
        public string Read(string path)
        {
            StreamReader sr=null ;
            StringBuilder sb = new StringBuilder();
            try
            {
                sr =new StreamReader(path, Encoding.UTF8);
                String line;
                while ((line = sr.ReadLine()) != null)
                {
                    sb.Append(line + "
");
                }
               
            }
            catch (Exception ex)
            {
            }
            finally
            {
                //清空缓冲区、关闭流
                if (null != sr)
                {
                    sr.Close();
                } 
            }
            return sb.ToString();
        }

        //读取文件
        public void Write(string path, string fileName, string content)
        {
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            FileStream fs=null ;
            try
            {
                fs = new FileStream(path + fileName, FileMode.Create);
                //获得字节数组
                byte[] data = System.Text.Encoding.UTF8.GetBytes(content);
                //开始写入
                fs.Write(data, 0, data.Length);
                
            }
            catch(Exception ex) {
            } 
             finally {
              
                //清空缓冲区、关闭流
                 if (null != fs)
                {
                    fs.Flush();
                    fs.Close();
                }
            }
        }
原文地址:https://www.cnblogs.com/zhaogaojian/p/9273024.html