StreamWriter not writing to file when called from task Scheduler C#

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.

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow