views:

84

answers:

2

Hi all,

I'm writing a unit test for file uploading feature of my web application. I mocked a test file, and save it in the "Test files" subdirectory of the directory that my test project resident in.

As I don't want to hard coded the file path. How can I know the directory of my project by code? I used @"..\Test files\test1.xml", but it doesn't work.

Thanks in advance!

A: 

Remember that your unit test project will be running relative from it's own bin directory, and not from the project directory. You can get the path to that bin directory using:

Assembly.GetExecutingAssembly().Location

However, the easiest thing to do is set your test files and folders to be copied to the output directory. Just click on your file in the solution explorer, hit F4, and change "Copy to Output Directory" to "Copy always" or "Copy if newer". The folder structure will automatically also be copied. Then your relative path statements will work correctly.

womp
I prefer your first suggestion. Which I can get where the assembly resident in. But when it comes to unit test. The binary is generated in a path like this:"%Visual Studio Project Directory%\[Project Name]\TestResults\[Computer name][Date time]\Out\*.dll"
Roy
I think there is no way but to get parse the project directory from this string.
Roy
A: 

I beleive HttpContext.Current.Request.PhysicalApplicationPath will give you the physical directory of your application root.

I would store the name of the sub directory in the web.config file, and then use System.IO.Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath,) to build the full path to the sub directory.

Jeremy