본문으로 바로가기

C# 날짜 Log 파일 만들기

category C# 2019. 8. 21. 15:38
반응형

안녕하세요

이번에는 C# 윈도폼을 실행시켰을 때 자동으로 Log 폴더를 만들고 오늘날짜로 저장하는 부분입니다.

 

string str 매개변수 부분은 로그파일 안에 쌓을 데이터를 받아오는 변수입니다

string 데이터를 쌓고싶으면 string 을 int 형을 쌓고싶으면 int로 받으시면 될 것 같습니다.

 

DirPath == Log 디렉터리(폴더) 만들기

FilePath == Log 파일 만들어 Log 디렉터리 안에 저장하기

 

나머지 조건은 로그폴더와 파일이 없을경우 만드는 부분이며

있을 경우 기존 Log파일에  데이터만 쌓는 부분입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
//로그 파일
        private void fn_LogWrite(string str)
        {
            string DirPath = Environment.CurrentDirectory + @"\Log";
            string FilePath = DirPath + "\\Log_" + DateTime.Today.ToString("MMdd"+ ".log";
            string temp;
 
            DirectoryInfo di = new DirectoryInfo(DirPath);
            FileInfo fi = new FileInfo(FilePath);
 
            try
            {
                if (!di.Exists) Directory.CreateDirectory(DirPath);
                if (!fi.Exists)
                {
                    using (StreamWriter sw = new StreamWriter(FilePath))
                    {
                        temp = string.Format("[{0}] {1}"DateTime.Now, str);
                        sw.WriteLine(temp);
                        sw.Close();
                    }
                }
                else
                {
                    using (StreamWriter sw = File.AppendText(FilePath))
                    {
                        temp = string.Format("[{0}] {1}"DateTime.Now, str);
                        sw.WriteLine(temp);
                        sw.Close();
                    }
                }
            }
            catch (Exception e)
            {
 
            }
        }
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

 

 

 

반응형