Write Log Files In C#


While working with complex coding we always have to face when error happening but no any message found, this case mostly occurred when we work with servers because in local system we can set some debugger points with help of editor tools or consoles, but when we work with server some time its become difficult to handle. In that case writing logs becomes handy.


Below code will simply write message if file exist and if not it creates them.

we can write them in many ways as below:-

1.
         public static void writelog(string Message)
         {
         
             string path = @"D:\USERFOLDER\ErrorLog_"+ DateTime.Now.AddDays(-1).ToString("M-d-yyyy") + ".txt";
             if (!File.Exists(path))
             {
                 File.Create(path).Dispose();
             
                 using (TextWriter tw = new StreamWriter(path))
                 {
                     tw.WriteLine(Message);
                 }

             }
             else if (File.Exists(path))
             {
                 File.AppendAllText(path, Message + Environment.NewLine);
             }
         }   


2. 

     public static void WriteLog(string strLog)
      {
            StreamWriter log;
            FileStream fileStream = null;
            DirectoryInfo logDirInfo = null;
            FileInfo logFileInfo;

        string logFilePath = "D:\\USERFOLDER\\";
        logFilePath = logFilePath + "ErrorLog_" + System.DateTime.Today.ToString("MM-dd-yyyy") + "." + "txt";           
        logFileInfo = new FileInfo(logFilePath);
        logDirInfo = new DirectoryInfo(logFileInfo.DirectoryName);
        if (!logDirInfo.Exists) logDirInfo.Create();
        if (!logFileInfo.Exists)
        {
            fileStream = logFileInfo.Create();
        }
        else
        {
            fileStream = new FileStream(logFilePath, FileMode.Append);
        }
        log = new StreamWriter(fileStream);
        log.WriteLine(strLog);
        log.Close();
    }