views:

267

answers:

2

I am trying to get the full path of a file in my unit test which is in a folder in my project. i tried using

Directory.GetCurrentDirectory();

but that returns the directory which my tests are running in. I want the directory of the project (or solution) without having to hard-code it in there. Then I can append the last part of the filename. Something similar to

System.getProperty("user.dir")

in java

A: 
string filePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
string folderPath = System.IO.Path.GetDirectoryName(filePath);

Also, it's best to tag your c# posts with win-forms, WPF or asp-net so that we can tell what platform you're working on.

David Lively
this gets the current working directory, ie, where the tests are running from, not the project path
OTisler
+1  A: 
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)

will get you the path of the running unit test DLL itself.

In order to access a file in a project subfolder, the simplest thing to do is mark the relevant files as Build Action = Content and Copy to Output Directory = Copy if newer. If you do that, then they will be copied to relative folders underneath the running assembly folder whenever you build the project. You can then calculate the physical path relative to the running assembly.

For example:

  • You have a text file located at <project root>\TestData\Data1.txt.
  • When you build the project in Debug mode, it will be copied to <project root>\bin\Debug\TestData\Data1.txt.
  • The physical path in your code will be Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "TestData\Data1.txt").
Christian Hayter
that seems like a lot of overhead to just reference a file. Is this the way most people use test data files in C#? I have dozens of files, some large, and it seems a little silly to have to copy them over and have them hang around in the output directory
OTisler
I don't know what `getProperty("user.dir")` does in Java so I can't comment. In .NET, when your assembly is executing, it is physically impossible to deduce the location of the source code directly. There might not *be* any source code on the machine, so how could you get at it? The only way to get at the files you want is to copy them from the source code to the running assembly location. Hence my answer.
Christian Hayter