본문 바로가기

Programing/.NET

[C#] Log파일 생성

 

지정경로에 폴더 및 파일이 없을 경우 파일을 생성하며 

.txt 파일로 로그를 생성하는 코드입니다.

 

public void LogWrite(string fileName, string msg) {
    string FilePath = "D:\\Logs\\" + fileName + "_" + DateTime.Today.ToString("yyyyMMdd") + ".txt";
    string DirPath = "D:\\Logs\\";
    string str = string.Empty;
    DirectoryInfo di = new DirectoryInfo(DirPath);
    FileInfo fi = new FileInfo(FilePath);
    try
    {
    	if (di.Exists != true) Directory.CreateDirectory(DirPath);
        if (fi.Exists != true)
        {
        	using (StreamWriter sw = new StreamWriter(FilePath))
            {
            	str = string.Format("[ {0} ] {1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff"), msg);
                sw.WriteLine(str);
                sw.Close();
            }
		}
		else
        {
        	using (StreamWriter sw = System.IO.File.AppendText(FilePath))
            {
            	str = string.Format("[ {0} ] {1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff"), msg);
                sw.WriteLine(str);
                sw.Close();
			}
		}
	}
    catch (Exception e)
    {
}