I have the following function, that accepts a string, and logs the string content to a log file.
private static void LogEvent(string sEvent)
{
sEvent = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "|" + sEvent;
Console.WriteLine(sEvent);
try
{
using (StreamWriter oStreamWriter = new System.IO.StreamWriter("MyService_" + DateTime.Now.ToString("yyyyMMdd") + ".log", true))
{
oStreamWriter.WriteLine(sEvent);
}
}
catch
{
}
}
When the program calling the function is manually run from the command line or by double clicking executable, the log file is either created or appended to.
The problem I have is I've set this program to be called from a task scheduler every 10 minutes, and for some reason the code is executing correctly, except the program is not creating or appending to the log file.
The scheduled task is calling the program using the same user permissions as when I manually ran the program.
Why is this happening, and how can I fix it.
You're currently trying to write to the process's current working directory - which may well be something like C:\Windows\System32
when it's executed by the task scheduler. You're not going to be able to write there.
Specify an absolute filename and I think you'll be fine. It's not clear where you do want to write to, but you should think about that carefully - ideally you should separate your executable files from the data that it generates. Consider using Environment.GetFolderPath
in conjunction with a suitable SpecialFolder
member (e.g. ApplicationData
.)
Note that using File.AppendAllText
would make the code simpler, mind you.
The answer by Jon Skeet is right that the problem is with working directory permission and you should use SpecialFolder to write logs but I will like to add one more point,
Never have empty catch
blocks like you did catch { }
for me this catch
statements sometime hides so many unknown problems.
I think they are something like teaser which says,
catch
{
// WHO CARES
}
Never hide this sort of exceptions under the carpet, take some action or inform the end user or flag somewhere what has happened. This will help the developer in later stages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With