c#文件流汇总

操作文件比较常见,项目中经常出现这样的需求:按每个月自动创建文件,并且向文件里面插入一些数据,那么我们将要分析,文件是否存在的情况;如果存在则直接打开文件流向文件中插入数据,如果不存在,则创建文件再插入数据的过程;在插入数据时,使用文件流的方式要考虑到中文乱码问题,以下简单实现方式

       public static void InsertData(string str)
        {
            string filePath = @"f:1.txt";

            if (!File.Exists(filePath))
            {
                using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                { 
                    StreamWriter sw = new StreamWriter(fs,Encoding.GetEncoding("GB2312"));
                    sw.Write(str);
                    sw.Close();
                    fs.Close();
                }
            }
            //以追加方式写入数据,并且只定编码格式,默认是UTF-8(中文乱码)
            using(StreamWriter tsw = new StreamWriter(filePath,true,Encoding.GetEncoding("GB2312")))
            {
                tsw.Write(System.Environment.NewLine);//换行符
                tsw.Write(str);
                tsw.Close();
            }
        }
原文地址:https://www.cnblogs.com/yxhblog/p/7207354.html