C#文件写入操作

        private const string File_Name = @"C:log.txt"; //const表示不能更改的变量,也可以当作常量
        static void Main(string[] args)
        {
            if(File.Exists(File_Name)){
                //向现有的文件中追加文本
                //使用using进行手动释放,超出花括弧的范围资源就i释放了
                using (StreamWriter w = File.AppendText(File_Name))  
                {
                    text("hello", w);
                    text("My baby", w);
                    w.Close();
                }

                Console.WriteLine("{0} aleady changed",File_Name);
                Console.ReadLine();
            }
            else
            //没有文件就创建文件,并写入内容
            {
                FileStream fs = new FileStream(File_Name,FileMode.Create);
                BinaryWriter bw = new BinaryWriter(fs);
                for (int i = 1; i < 11; i++)
                {
                    bw.Write("a");
                }
                bw.Close();  //使用完成后释放资源
                fs.Close();
            }
        }

        public static void text(string message, TextWriter w)
        {
            w.Write("
log message:");
            w.WriteLine(" :{0}",message);
            w.Flush();
        } 
越努力,越幸运!
原文地址:https://www.cnblogs.com/hubbert123/p/6427447.html