How does default/relative path resolution work in .NET?

后端 未结 4 632
南旧
南旧 2021-02-08 23:31

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

4条回答
  •  滥情空心
    2021-02-09 00:18

    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.

提交回复
热议问题