-2

I want to keep logs exception from catch and send to database or text file ?

try
{
}
catch (Exception ex)
{
   MessageBox.Show(ex.Message);  
}

thank you

  • 1
    Instead of using a `MessageBox`, you'll need to open up a filestream or socket to and send the exception string through that. You'll need to pay close attention to what encoding you use – [the default encoding may vary depending on your system](https://msdn.microsoft.com/en-us/library/system.text.encoding.default%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396) – Nicholas Miller Dec 21 '17 at 05:18
  • Take a look at using a logging service. I usually use [log4net](https://logging.apache.org/log4net/). Here is [an example](https://stackify.com/log4net-guide-dotnet-logging/) you can check out. – burnttoast11 Dec 21 '17 at 05:28

2 Answers2

0

Simply, create object of your database context if you are using Entity framework and insert it in your table(e.g. a table containing(id, Exception Name, innermessage, error number, CreatedDateTime, etc)).

catch (Exception ex)
{
   DatabaseEntity DbObj = new DatabaseEntity();
   ExceptionTable ExObj = new ExceptionTable();
   ExObj.ExceptionName = ex.Message;
   ExObj.InnerException = ex.InnerException;
   .....
   //Code according to your need
   .....

   DbObj.ExceptionTable.Add(ExObj);
   DbObj.SaveChanges();
   MessageBox.Show(ex.Message);  
}

you may follow this How to Log Exception in a file?, this may help you

0

This will create a text file or append the txt if it is already present with the date and time of the exception thrown. I hope this is what your were looking for.

catch(Exception Ex)
            {
                StreamWriter sw = null;
                String Logfile = "C:\ExceptionLog.txt";
                if (!System.IO.File.Exists(LogFile))
                {
                    sw = File.CreateText(LogFile);
                    sw.WriteLine(String.Format("Exception\t DateTime"));

                }
                else
                {
                    sw = File.AppendText(@"C:\ExceptionLog.txt");
                }

                sw.WriteLine(String.Format("{0}\t {1}", Ex, 
                    DateTime.Now.ToString("MM/dd/yyy HH:mm:ss"));
                sw.Close();
            }
shrot
  • 145
  • 1
  • 9