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.