In my recent work, I want to make a small tool for client reminders; Naturally, the winform program must read the configuration file of the same directory as the application (not the exe.config file);
To read the directory where the current application is located, I immediately thought of System.Environment.CurrentDirectory to get the current working directory. The program seems to run flawlessly;
When I came to work the next morning, it popped up: "Read configuration file missing". The app adds boot auto-start. This message pops up to read the configuration file failure, immediately check whether the configuration file in the application directory has been deleted by itself. After checking, I found that the file was still there, and I exited the program and ran it again
Still fine, no pop-up read profile missing. Then see if the path of the boot entry in the registry is not in my directory? Looking at the path file, it's all right. A little confused? Log out of the computer and try to restart it still pops up the configuration file is missing. The reason for not being able to find the way will be taken directly
MessageBox, the program runs and finds that the path is indeed this path.
Add the MessageBox code and continue to boot the test. When I booted up, I found that the current directory that popped up was C:\Windows\System32, and I was puzzled at once. I thought to myself, could it be that Lao Tzu's program ran down to system32? Checking the registry and sysetm32 doesn't have my app. Finally, I thought that there should be a problem with the code to get the path.
After repeated testing, it was found that System.Environment.CurrentDirectory is indeed to get the current directory, but if program A calls program B and program B uses System.Environment.CurrentDirectory to get the directory. Then the directory obtained in the B program is no longer the directory where the B application is located; It becomes the directory where A is located. It is not difficult to find that the directory that pops up when I boot is C:\Windows\System32 because the boot self-startup program is also called by a process in Windows.
Therefore, if the winform program wants to obtain the directory where the current application is located, it is best not to use System.Environment.CurrentDirectory. Instead, it is: Application.StartupPath This way, it doesn't matter who calls it.
Test code:
Transferred from:The hyperlink login is visible.
|