0

I am trying to publish a service and I am having issues (on the networkers side), so I am trying to write some exception logging to help them along.

StreamWriter log;
if (!File.Exists("C:\\Projects\\logfile.txt"))
{
    log = new StreamWriter("C:\\Projects\\logfile.txt");
}
else
{
    log = File.AppendText("C:\\Projects\\logfile.txt");
    throw new Exception();
}

log.WriteLine(DateTime.Now);
log.WriteLine("StartProcessing");
log.WriteLine();
log.Close();

I have this set up about 4 different places because I feel that's where the error is...

My big question is if I need to write something to modify the file after it's been created, because currently only the first place I put this code actually puts in the WriteLine stuff.

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
PapaNer
  • 31
  • 2
  • 7
  • You can open the file after it's been created to write more log entries... if that's what you're asking about. See here. http://msdn.microsoft.com/en-us/library/b9skfh7s(v=vs.110).aspx I'm not 100% sure I get your question, though. – eddie_cat Aug 05 '14 at 15:18
  • Your question is a little confusing, are you worried that you may try to write elsewhere when the file hasn't been created yet? If so, you could use one class to handle all of your writes, and have it check that the file exists before actually doing the write. Writes are also not thread safe, you may get issues with the file being locked when trying to write. By moving everything to one class you could lock the write function to make sure two things don't write at the same time. – vesuvious Aug 05 '14 at 15:22
  • 1
    @eddie_cat Hah! That is it! My issue was that out of the 4 instances of this code, only the first one worked, and I didn't really know how to ask it in an easier way. I will try this and let you know if it worked. After visiting the link, it seems like it will. I appreciate you taking the time! – PapaNer Aug 05 '14 at 15:23
  • Well, you're throwing an exception if the file already exists. And if you want to append to the file you can also use the `StreamWriter(string,bool)` constructor ([documentation](http://msdn.microsoft.com/en-us/library/36b035cb(v=vs.110).aspx)), and set the second argument to `true` to append to the file. I'd also suggest `using (var log = new StreamWriter(...,true) { ... }` to manage the stream, so that if you throw an exception the file is closed. This latter point may be an issue you're having as well. – cod3monk3y Aug 05 '14 at 15:27
  • 1
    Why `throw new Exception();` in `else {}`? If the file exists, no logging will take place anymore. – AlexD Aug 05 '14 at 15:27
  • @AlexD I just saw that. I have a coworker that was trying to fasttrack this with me (I'm fairly new to this world) and he tossed that in there and I didn't realize exactly what it was. Thank you. – PapaNer Aug 05 '14 at 15:33

0 Answers0