views:

446

answers:

2

Hi,

I am trying to create unittests that can be shared amongst my development team so I need to have all paths in the project be relative.

Where this is giving me trouble is with the HttpWebRequest class. I want it to serve static testdata from a file in the local filesystem.

I'd like to do something like this:

file:///./TestData/test.html

But that just produces C:\TestData\test.html and a DirectoryNotFoundException.

The code for the HttpWebRequest looks like this:

var request = HttpWebRequest.Create(uri);
var response = request.GetResponse();
var responseStream = new StreamReader(response.GetResponseStream());
return responseStream.ReadToEnd();

How can I convince C# to resolve a relative path without breaking the Uri syntax?

greetings Daniel

+1  A: 

Is the file you are trying to server have a relative path compared to any of the assemblies in your project? If so then you could build a non-relative URL based on the path of one of the assemblies and return that to the caller.

For Example:

var basePath = Path.GetDirectoryName(typeof(MyType).Assembly.Location);
var fullPath = Path.Combine(basePath, @"TestData\test.html");
return new Uri(fullPath);
JaredPar
Why would you use typeof(MyType).Assembly.Location instead of Environment.CurrentDirectory?
Daniel Schaffer
@Daniel, it's very easy for a program to alter Environment.CurrentDirectory and thus makes a solution depending on that fragile. It's very difficult/impossible to change the path of an assembly.
JaredPar
A: 

Why do you need a webrequest if it's on the file system? you can just open it with File.ReadAllText(path)

BFree
The final production system would query data from a remote server.During special tests I want to serve local files acting like a remote server.
Tigraine
yea but all this method is doing is returning the HTML as a string so for testing purposes File.ReadAllText should suffice IMO
BFree