• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 288
  • Last Modified:

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

0
Camillia
Asked:
Camillia
1 Solution
 
Seaton007Commented:
0
 
DustinKikuchiCommented:
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
 
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

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now