Writing errors to a textfile

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

LVL 8
CamilliaAsked:
Who is Participating?
 
DustinKikuchiConnect With a Mentor 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

0
 
Seaton007Commented:
0
 
CamilliaAuthor 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

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.