How do I get the relative root path of an application being developed in C # .NET MVC?

I have several unit tests that require files from a project to be used to run the unit tests. These files are just images. I need to get an image file using some function inside C # other than inserting the full path like below.

string filePath = @"C:\Users\user1\Documents\Visual Studio 2008\Projects\app1\app1.Tests\Fakes\test_files\test-image.jpg";

      

I would rather do something like:

string filePath = app.path + "\Fakes\test_files\test-images.jpg"

      

How can i do this?

Thank!

+2


source to share


3 answers


If you are asking a question about getting these files at runtime ... you don't want to. You should deploy these files as part of the build process as soon as possible so that they end up in a predictable place when compared to your compiled binaries and other content.

In Visual Studio, you can set any project file Copy to Output Directory so that it will place the file in your output folder.

Copy to Output Directory Screenshot http://i33.tinypic.com/aky4j7.png




Since it appears that you want these files to be part of your unit tests, you would like to use the MSTest attribute instead [DeploymentItem]

. This will place the files in your test directory at runtime. Read about Testing Deployment on MSDN .

+2


source


To be clear, this will not be a unit test. A unit test shouldn't rely on the environment. Nothing in the database, filesystem, etc. Should not be used. A unit test should only be used to test one block of code. This is because if someone pulls the source and runs the unit tests (the first thing you need to do after getting the source) it won't work. Before the tests pass, they must create an environment. These are called integration tests.



That being said, you can set up a variable if it is in only one class, or app.config if it is in multiple classes. Then you can add the path there as the default path and use it as "app.path".

0


source


I don't like the top-rated above answer because it doesn't answer the original question.

There are legitimate reasons to want the root path of an ASP.NET web application, including the MVC variety. For example, I need this so that I can pass a "URI pattern" which later uses an XSL transformation to resolve a dynamically served XML document (using the document Xpath function).

For a complete URI, you can do a string operation on this. Request.Url.AbsoluteUri from inside your controller / page.

Use this.Request.Path for the current path or this.Request.ApplicationPAth for the application root path.

0


source







All Articles