C# 读写文本文件

        //读取文件
        public string Read(string path)
        {
            StreamReader sr = new StreamReader(path, Encoding.UTF8);
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = sr.ReadLine()) != null)
            {
                sb.Append(line+"\r\n");
            }
            return sb.ToString();
        }
        //读取文件
        public void Write(string path,string fileName,string content)
        {
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            FileStream fs = new FileStream(path + fileName, FileMode.Create);
            //获得字节数组
            byte[] data = System.Text.Encoding.UTF8.GetBytes(content);
            //开始写入
            fs.Write(data, 0, data.Length);
            //清空缓冲区、关闭流
            fs.Flush();
            fs.Close();
        }

猜你喜欢

转载自www.cnblogs.com/zhaogaojian/p/9273024.html
今日推荐