简体   繁体   中英

Preference between Application.StartupPath and AppDomain.CurrentDomain.BaseDirectory when writing a windows forms application

I came across tons of ways to extract the current directory in C#.

I am trying to get the directory of the Windows Forms application that I am writing. My application tends to be called by other processes so Environment.CurrentDirectory didn't work for me.

After doing a quick search and some testing, AppDomain.CurrentDomain.BaseDirectory and Application.StartupPath seems to be the best ways to go and works fine on my end.

I need to know which one is better to use as well as any issues that might arise when I use one over the other.

Flip a coin, they are always the same in a well-behaved Winforms app. Technically it can be screwed up, a .config file can change the .BaseDirectory. Not an issue with StartupPath, it is guaranteed to always return the path of the EXE file regardless of configuration, it uses a winapi function under the hood.

So if the file location is relative from the EXE file, like it normally is, then StartupPath is "best". Just keep in mind that you can only ever expect to be able to read from such a file. Writing works fine when you debug but not after you deploy it. Programs don't have write access to C:\\Program Files. In such a case using AppData is important, use Environment.GetFolderPath(). Or a file share if data is precious and needs to be backed up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM