3

How can I programmatically get the path of the current project in my C# code?

Do I have any preprocessor directives for this? Or any macros?

Note: I don't need the path of the current executing assembly, but rather a path of the project, from which this assembly was compiled.

Note (2) - What I'm trying to achieve: I have several files that are compiled as embedded resources. I load and use them in the runtime. I would like to create a "debug" mode, in which the files are loaded from their original location on disk and not from the resource stream. This would enable me to fast-edit the files for test purposes without the need to recompile the assembly. Since the assembly is copied to a different location, outside the project from which it was compiled, in the "debug" mode I can't load the files using relative path.

Aryéh Radlé
  • 1,310
  • 14
  • 31
  • 1
    Hmm, I bet the generated debugging symbols might contain information like that. – cbr Jan 09 '17 at 15:39
  • @cubrr Good idea. Is there a way to query the pdb of the current assembly? – Aryéh Radlé Jan 09 '17 at 15:40
  • I'm not sure. Some more ideas here: [_Is there a way to find exe compilation path_](http://stackoverflow.com/a/35373180/996081) – cbr Jan 09 '17 at 15:41
  • 1
    As for getting the PDB, found these two: [_How to find corresponding .pdb inside .NET assembly?_](http://stackoverflow.com/questions/38821662/how-to-find-corresponding-pdb-inside-net-assembly) and [_How to read source path from pdb_](http://stackoverflow.com/questions/9585192/how-to-read-source-path-from-pdb) – cbr Jan 09 '17 at 15:44
  • As a Post Build Step, you could run a simple exe to write the build path into a text-document that you ship with your application (it's available as a macro) - do you have any obfuscation or security requirements, or is there some other reason this wouldn't suffice? Please expand your answer with the reason why you want to do this, to aid us in answering :) – RB. Jan 09 '17 at 15:44
  • @RB. In deed I do. – Aryéh Radlé Jan 09 '17 at 15:48
  • @ArieR Could you edit your answer to explain (a) What those reasons are, and (b) why you are trying to achieve this? It's really hard to help without those crucial bits of information... – RB. Jan 09 '17 at 15:52
  • @RB. Updated, see above – Aryéh Radlé Jan 09 '17 at 15:59

2 Answers2

6

You might be able to make use of the CallerFilePathAttribute.

https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.callerfilepathattribute(v=vs.110).aspx

Mike
  • 435
  • 2
  • 7
0
string fileName = "SampleFile.txt";
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, LocalConstants.EMAIL_PATH, fileName);

C:\****\****\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsFormsApplication1\bin\Debug\Emails\SampleFile.txt
  • 2
    That will be the runtime path, not the compile time path. The two will happen to be the same when a project is run from Visual Studio of course. – RB. Jan 09 '17 at 16:00