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

后端 未结 4 630
南旧
南旧 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.

    0 讨论(0)
  • 2021-02-09 00:19

    You can use this to specify a path that resides at the same path of your exe @"..\CAISLog.csv". Please note that the double dots refer to the parent directory of where ever your .exe lies.

    RWendi

    0 讨论(0)
  • 2021-02-09 00:20

    Relative Path resolution never works against the path of the launching executable. It always works against the process' Current Directory, and you can't really expect that to always be set to the directory the .exe lives in.

    If you need that behavior, then take care to find out the right path on your own and provide a fully qualified path to the file operations.

    0 讨论(0)
  • 2021-02-09 00:24

    It is based on the current working directory which may or may not be the same as where your application resides, especially if started from a different program or a shortcut with a different working directory.

    Rather than hard code the path, get the path to your program and use it. You can do this with something like this

    Assembly ass = Assembly.GetEntryAssembly();
    string dir = Path.GetDirectoryName(ass.Location);
    string filename = Path.Combine( dir, "CAISLog.csv" );
    

    This assumes that the entry assembly is where your file is. If not, you can change up getting the assembly for something like;

    Assembly ass = Assembly.GetAssembly( typeof( AClassInYourAssembly ) );
    
    0 讨论(0)
提交回复
热议问题