Monday, September 15, 2014

Writing the log file from asp.net

Step1:- Copy these two methods into code file and access the those methods in your project where you want


public void ExceptionHandler(string ExceptionMessage)
        {
            try
            {
                // string root = Directory.GetCurrentDirectory() + "\\Log";
                // if (!Directory.Exists(root))
                // {
                // Directory.CreateDirectory(root);
                // }

                string root = "C:\\Log\\";
                string path = root + "SampleLog" + System.DateTime.Now.ToString("ddMMyyy") + ".txt";

                CallExceptionHandler(path, ExceptionMessage);

            }
            catch (Exception)
            { }
        }


        private void CallExceptionHandler(string strPath, string strException)
        {
            FileStream fsFile = null;
            StreamWriter swWriter = null;
            try
            {
                if (File.Exists(strPath))
                {
                    fsFile = new FileStream(strPath, FileMode.Append, FileAccess.Write);
                    swWriter = new StreamWriter(fsFile);
                    swWriter.WriteLine(Environment.NewLine + DateTime.Now.ToString("dd-MMM-yyyy hh:mm:ss") + "-----------" + Environment.NewLine);

                    swWriter.WriteLine(strException);
                }
                else
                {
                    fsFile = new FileStream(strPath, FileMode.Create, FileAccess.Write);
                    swWriter = new StreamWriter(fsFile);
                    swWriter.WriteLine(strException);
                }
                swWriter.Flush();

            }
            catch (Exception)
            {
            }
            finally
            {
                swWriter.Close(); fsFile.Close(); swWriter.Dispose(); fsFile.Dispose();
            }
        }


No comments:

Post a Comment