1

I want to get the folder in which my current project is located.

The only way I know to access something in my current folder is this:

System.Reflection.Assembly.GetExecutingAssembly().Location

However, that takes me to an address of the form:

Z:\path\to\my\things\MyProject\bin\x86\Debug\MyProject.dll

Instead of getting to this address, I would just want to get to:

Z:\path\to\my\things\MyProject

I realised that I can achieve that by doing this:

Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "../../..")

However, I don't like that I have to hardcode "../../..".

Is there a way of achieving the same thing without the hardcoding?

EDIT

If I try Environment.CurrentDirectory or System.IO.Directory.GetCurrentDirectory();, as suggested in this question, I get to C:\Windows\System32, so that's not helpful at all.

bsky
  • 19,326
  • 49
  • 155
  • 270
  • 2
    the problem is that the c# runtime has no way of knowing this. It doesnt know what you source layout looked like at compile time – pm100 Dec 15 '17 at 16:43
  • 5
    Possible duplicate of [How do you get the current project directory from C# code when creating a custom MSBuild task?](https://stackoverflow.com/questions/816566/how-do-you-get-the-current-project-directory-from-c-sharp-code-when-creating-a-c) – Kevin Bourassa-Houle Dec 15 '17 at 16:43
  • 1
    But for what purpose do you need to know this folder while your code is running? – Steve Dec 15 '17 at 16:47
  • 1
    @Steve I just want to read a file within a unit test. – bsky Dec 15 '17 at 16:49
  • 1
    You want to “read a file within a unit test”? That's a pretty important thing to not tell us! Is “a file” part of the application project or the unit test project? MSTest stores the path to the test output directory in `TestTools.UnitTesting.TestContext.TestDir`, is that what you are looking for? Any other important things you neglected to mention? – Dour High Arch Dec 15 '17 at 16:58

1 Answers1

2

Based on your comment I would leave the code as-is - you're right that hardcoding the ..\..\..\ isn't the way to go - and getting the path to the executing assembly is the correct way to do this.

Instead what you should for you unit test project is include the test file in your test project, and set the properties of the file to be "Content" and "Copy to output directory"

That will move the test file into the same location as the DLL, and then you'll be able to reference it correctly.

Zhaph - Ben Duguid
  • 26,785
  • 5
  • 80
  • 117