c#有则追加,无则新建TXT内容,换行

using System.IO;

namespace Hydor1
{
    class CreatFile
    {
        public void creatf(string str, string name)
        {
            //获取当前日期
            string s = DateTime.Now.ToString("yyyy-MM-dd");
            string time = DateTime.Now.ToLongTimeString().ToString();
            string path = System.Windows.Forms.Application.StartupPath + @"../../../Log";

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            if (!File.Exists(System.Windows.Forms.Application.StartupPath + @"../../../Log/" + s + ".txt"))
            {
                FileStream fs = new FileStream(System.Windows.Forms.Application.StartupPath + @"../../../Log/" + s + ".txt", FileMode.Create, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs);
                long fl = fs.Length;
                fs.Seek(fl, SeekOrigin.End);
                sw.WriteLine("时间        操作员姓名        操作
");//开始写入值
                sw.WriteLine(time + "      " + name + "      " + str + "
");//开始写入值
                sw.Close();
                fs.Close();


            }
            else
            {
                FileStream fs = new FileStream(System.Windows.Forms.Application.StartupPath + @"../../../Log/" + s + ".txt", FileMode.Open, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs);
                long fl = fs.Length;
                fs.Seek(fl, SeekOrigin.Begin);

                sw.WriteLine(time + "      " + name + "      " + str + "
");//开始写入值
                sw.Close();
                fs.Close();
            }
        }

    }

}
原文地址:https://www.cnblogs.com/janeaiai/p/5072590.html