Roy
Roy

Reputation: 2323

Visual studio project directory

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!

Upvotes: 2

Views: 4126

Answers (3)

Just another way:

int ix = Application.StartupPath.LastIndexOf(Application.ProductName);
string s = Application.StartupPath.Remove(ix + Application.ProductName.Length + 1);

edit: After I posted it I saw that the question was for web applications, while my solution is for Windows Forms.

Upvotes: 0

Jeremy
Jeremy

Reputation: 46322

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.

Upvotes: 0

womp
womp

Reputation: 116977

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.

Upvotes: 4

Related Questions