问题
I have a C# console application that runs as a scheduled task within Windows Task Scheduler. This console app writes to a log file that when runs within debug mode creates and writes to the file within the application folder itself. However, when it runs in the task scheduler it throws an error saying that access is denied because it is trying to write to the same log file, but for some reason it is trying to write to it within the windows\system32 folder. Why would this be happening? And how would I correct this?
Here is the code snippet that assigns a StreamWriter to the log file:
static void Main(string[] args)
{
using (_swrtr = File.AppendText("gapi_gen_log.txt"))
{
_swrtr.Write("\r\n");
_swrtr.Write("\r\nGOOGLE CALENDAR:");
_swrtr.Write("\r\n\tDate Time - " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString());
start();
}
}
I also tried but this didn't work:
string dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
using (_swrtr = File.AppendText(dir + "gapi_gen_log.txt"))
{
_swrtr.Write("\r\n");
_swrtr.Write("\r\nGOOGLE CALENDAR:");
_swrtr.Write("\r\n\tDate Time - " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString());
start();
}
回答1:
This is happening because you are not specifying a directory for your log file, so it's assuming the directory where the parent executable resides which, while you're debugging, is your debug output folder and when you're running it from the task scheduler, is the "c:\windows\system32" folder.
You could provide a path to the directory like this:
File.AppendText(@"c:\MyLogFiles\gapi_gen_log.txt")
来源:https://stackoverflow.com/questions/29896874/file-appendtext-attempting-to-write-to-wrong-location