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();
            }
        }

    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM