We help IT Professionals succeed at work.

Writing errors to a textfile

Camillia
Camillia asked
on
I've been looking at examples and not sure if I'm doing this correctly. I want to write errors to a textfile. I want to write to textfile but also display an error msg to user. I think what I have is wrong because what if the file exists...then if statement wont be execuste. This is what I have;

private void SaveRecords()
{
   try
    {
       //call save routine in Return Class
         Return.Save(...);
    }
    catch (Exception ex)
    {
        
       string path = @"c:\SaveReturnItem.txt";
                if (!File.Exists(path))
                 {
                    // Create a file to write to.
                    using (StreamWriter sw = File.CreateText(path))
                    {
                        sw.WriteLine(DateTime.Now);
                        sw.WriteLine(e.Message);
                        sw.WriteLine("--------------------");
                    }
                }

      MessageBox.Show("Record could not be saved.");
      
    }
 
}


// in Return class

public void Save(...)
{
   try
    {
 
    }
    catch (Exception ex)
    {
       throw ex;
    }

}

Open in new window

Comment
Watch Question

CERTIFIED EXPERT

Commented:
You're correct about the reasoning behind the issue.  Once the file exists, you're no longer entering your code block that writes to the file.

For that you'll need to add something along the lines of:
else
{
   using (StreamWriter sw = File.AppendText(path))
   {
      sw.WriteLine(DateTime.Now);
      sw.WriteLine(e.Message);
      sw.WriteLine("--------------------");
   }
}

Open in new window

CERTIFIED EXPERT

Author

Commented:
the microsoft site isnt good. Now, should I use File.Append or File.Open. This is what i have now


//log to textfile
                string path = @"c:\SaveReturnItem.txt";
                if (!File.Exists(path))
                { StreamWriter sw = File.CreateText(path); sw.Close(); }

                using (StreamWriter sw = new StreamWriter(new FileStream(path, FileMode.Open)))
                {
                    sw.WriteLine(DateTime.Now);
                    sw.WriteLine(e.Message);
                    sw.WriteLine("--------------------");
                    sw.Close();
                }

Open in new window

Explore More ContentExplore courses, solutions, and other research materials related to this topic.