Klaw
Klaw

Reputation: 7887

.NET: Getting the absolute path for a file when running VS Team Test

Currently I have a test class called TestClass.cs in C:\Projects\TestProject\TestClass.cs
I also have an Xml file in C:\Projects\TestProject\config\config.xml

In TestClass.cs, I have a test method to load the Xml from the filesystem like so:

XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(Path.Combine(Assembly.GetExecutingAssembly().Location, "config\config.xml"));

Unfortunately, the Location property gives me the value:
C:\Projects\TestProject\TestResults\klaw_[computernamehere] [time here]\

instead of what I want, which is C:\Projects\TestProject\

I've tried Assembly.GetExecutingAssembly().CodeBase as well with similar results.

Any ideas?

Upvotes: 3

Views: 1077

Answers (4)

Aaron Weiker
Aaron Weiker

Reputation: 2531

In addition to marking an item with [DeploymentItem], you will also need to make sure your test run configuration has Enable Deployment checked along with the directory of where to grab items from.

Upvotes: 1

Justin Bannister
Justin Bannister

Reputation: 618

Since this is a test, how about making the file an embedded resource? You can then read the embedded resource at runtime with the following code:

Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource);

The resource is normally the namespace + filename. But you can work this out by running the following code in the debugger:

AssemblyGetExecutingAssembly().GetManifestResourceNames();

This returns a list of embedded resources.

Upvotes: 2

David M
David M

Reputation: 72870

You need to mark this file with the DeploymentItemAttribute if you're using MSTest. This means it will be copied with the DLL.

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1062780

Well, it is telling the truth. Unlike NUnit / TestDriven.NET, etc - MSTest copied things around into a different folder for each test. Which is (IMO) a pain - for example, you need to either attribute files to include ([DeploymentItem]), or specify them in the testrunconfig (properties -> Deployment -> Add File...).

Contrast this to TestDriven.NET, where you could use the "Copy to Output Directory" flag.

Upvotes: 1

Related Questions