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("时间        操作员姓名        操作\n");//开始写入值
                sw.WriteLine(time + "      " + name + "      " + str + "\n");//开始写入值
                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 + "\n");//开始写入值
                sw.Close();
                fs.Close();
            }
        }

    }

}

 

posted @ 2015-12-24 11:52  JaneAi  阅读(2812)  评论(0编辑  收藏  举报