In my C# code, I reference to an XML file "file.xml", which is in the same directory as the executable itself, using XmlDocument.
The application runs perfectly well in VS, but when I try to run the application using Task Scheduler, I get a System.IO.FileNotFoundException
, even though everything's the same.
I reference to the file using @".\file.xml"
. Is this some weird stuff specific to Task Scheduler? Appropriate permissions are used.
Try to set startup directory for the task. You can set in Task Scheduler.
Select Task -> Right Click -> Properties -> Actions Tab -> Select Action -> Edit -> Start in (optional)
I met the same problem, and i tried to print out the various path that .Net sets for the program, here's the result on my machine
AppDomain.CurrentDomain.BaseDirectory: <my program folder>
Directory.GetCurrentDirectory();: C:\Windows\system32
Environment.CurrentDirectory: C:\Windows\system32
so you probably want to use AppDomain.CurrentDomain.BaseDirectory
to locate your file, like this:
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "file.xml");
// use this path to open xml and do your work with it
You need to set the application's current working directory to the correct path. I don't know what it is when Task Scheduler launches your application, but it's never a good idea to assume.
You can do so with Directory.SetCurrentDirectory()
.
Alternatively, you can use an absolute path to the XML file.
Try refering to your document by using
Application.StartupPath(@"\file.xml")