File.AppendText attempting to write to wrong location

為{幸葍}努か 提交于 2019-12-04 07:09:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!