Thursday, 17 March 2016

Creating Error Log file in C#


// If you want store error in notepad file , can use this code .

        public bool ErrorLog(string ErrorMessage)
        {

            try
            {
             
            string     lstrErrFilePath = System.Windows.Forms.Application.StartupPath + "\\DBLog" + "\\" + System.DateTime.Now.ToString("dd-MMM-yyy") + ".txt";
                if (!(Directory.Exists(System.Windows.Forms.Application.StartupPath + "\\DBLog")))
                {
                    Directory.CreateDirectory(System.Windows.Forms.Application.StartupPath + "\\DBLog");
                }
                FileStream tmpFile;
                if (File.Exists(lstrErrFilePath))
                {


                    tmpFile = new FileStream(lstrErrFilePath, FileMode.Append);
                    StreamWriter sw = new StreamWriter(tmpFile);
                    sw.WriteLine(" DT:" + System.DateTime.Now.ToString("dd-MMM-yyy hh:mm:ss") + "DB Error Message:" + ErrorMessage);
                    sw.Close();

                }
                else
                {
                    tmpFile = new FileStream(lstrErrFilePath, FileMode.Create);
                    StreamWriter sw = new StreamWriter(tmpFile);
                    sw.WriteLine(" DT:" + System.DateTime.Now.ToString("dd-MMM-yyy hh:mm:ss") + "DB Error Message:" + ErrorMessage);
                    sw.Close();
                }

                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
            finally
            {

            }
        }

No comments:

Post a Comment