What is the best method of getting the path the C# executable is running from?
I need to use it for temp folders etc and currently I\'m using:
Path.G
Try:
Application.StartupPath
It should return the path without the executable filename.
If the assembly has been shadow copied then Assembly.Location
will point to the shadow copy of the dll.
If you want to know the location of the build output directory use Assembly.CodeBase
, i.e.:
Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath)
Useful if you want to access other resources from the directory of the assembly for example when running test suite.
Not an accurate answer to your question, however I would suggest to have a look at:
Path.GetTempFileName()
http://msdn.microsoft.com/en-us/library/system.io.path.gettempfilename.aspx
Try with Environment.CurrentDirectory
This returns the folder of your currently working directory.
For temp folders etc. you should NOT use the executing directory for security reasons... MS has something built-in for this:
You can use ApplicationData
(for roaming users) or LocalApplicationData
(for non-roaming users) or CommonApplicationData
(for non-user-related things) from Environment.SpecialFolder
- anything (files+folders) you create within those folders is already setup with the needed permissions/rights for the user running you app - nobody else (except perhaps Administrator) can go there... to make it even more secure you could encrypt data you put there...
see http://msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx
string executableLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string txtfile = Path.Combine(executableLocation, "example.txt");