So... I used to think that when you accessed a file but specified the name without a path (CAISLog.csv in my case) that .NET would expect the file to reside at the same path as
When an application (WinForms) starts up, the Environment.CurrentDirectory
contains the path to the application folder (i.e. the folder that contains the .exe assembly). Using any of the File Dialogs, ex. OpenFileDialog
, SaveFileDialog
, etc. will cause the current directory to change (if a different folder was selected).
When running a Windows Service, its containing folder is C:\Windows\System32, as that is the System folder and it is the System (i.e. the Operation System) that is actually running your Windows Service.
Note that specifying a relative path in most of the System.IO
objects, will fall back to using the Environment.CurrentDirectory
property.
As mentioned, there are several ways to obtain the path of the service executable, using Assembly.GetEntryAssembly()
or Assembly.GetExecutingAssembly()
and then using either the Location
property or the CodeBase
property (be aware that this is the file path, not directory, of the executable).
Another option is to use:
`System.IO.Directory.SetCurrentDirectory( System.AppDomain.CurrentDomain.BaseDirectory );`
Make the call in the Service's OnStart
method, applying it to the whole application.