Just recently I had a problem whereby there was a case which resulted in the current working directory changing before some of my code had run. As I hadn’t catered for this case it came up with a crash which was easily fixed by getting the current application path and then combining this with the filename which I wished to access. Heres the code that I used to acheive this in a nice clean fashion and create a path to a configuration file (configurationFilename):
Uri uri = new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase);
string fullConfigurationFilename = Path.Combine(Path.GetDirectoryName(uri.AbsolutePath), configurationFilename);
fullConfigurationFilename = HttpUtility.UrlDecode(fullConfigurationFilename);
By using reflection to get the location of the currently executing assembly I am not relying on the actual .exe location (or website location in fact), but instead using the actual dll’s location from which the current code is running. You might wish to use the actual application’s path or the website root path, but in the scenario that I am using this in, the assembly’s path is exactly what I wanted.