Rano AH

Rano AH

  • NA
  • 176
  • 109.2k

Log file

Aug 28 2013 9:01 AM

Hi

I implemented the below function to create a log file that captures all errors that might occurred while my code is being executed. I call it in each catch block.

Example:

catch (IndexOutOfRangeException ex)
                    {
                        MessageBox.Show("File seems to be empty, skipping this file);
                        string exception = "File seems to be empty, skipping this file");
                        SkippedFiles += 1;
                        logFile(exception, file, SkippedFiles);
                        continue;
   }

public void logFile(string ExceptionName, string fileName, int SkippedFiles)
        {

            StreamWriter log;
            if (!File.Exists("logFile.txt"))
            {
                log = new StreamWriter("logFile.txt");
            }
            else
            {
                log = File.AppendText("logFile.txt");
            }

            //Write to the file:
            log.WriteLine("Data Time: " + DateTime.Now);
            log.WriteLine("File Name: " + fileName);
            log.WriteLine("Number of Skipped Files: " + SkippedFiles);
            log.WriteLine("Exception Name: " + ExceptionName);
            log.WriteLine("End of the report");
            log.WriteLine("\n===========================================================");
            //close the stream:
            log.Close();
        }

Since I have multiple catch blocks, Is this the right way to call the log function?
Another thing. this will create the log file in the Bin\debug Dirctory. How to create it in any other directory or create it inside a folder which needs to be created (if errors occurred)


Answers (1)