3

I am working on Unit tests that test a method in an application that produces a file. So I decided to put an expected file in a directory called Resource/Empower/. The resource folder is at the same level as the bin folder of the Unit Test project.

Now what I want to do is get the path of the file name. I cannot hard code because I don't know exactly about the drives on the build server.

So how do I get the relative path of the file. Lets say if the file Name is expectedMasterFileSetUp.txt?

I want the path Resource/Empower/ExpectedMasterFileSetUp.txt

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
SaiBand
  • 5,025
  • 15
  • 57
  • 76

2 Answers2

3

Why use a URI?

string AbsolutePathRelativeToEntryPointLocation( string relativePath )
{
  Assembly entryPoint    = Assembly.GetEntryAssembly() ;
  string   basePath      = Path.GetDirectoryName( entryPoint.Location ) ;
  string   combinedPath  = Path.Combine( basePath , relativePath )      ;
  string   canonicalPath = Path.GetFullPath( combinedPath ) ;

  return canonicalPath ;
}
Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
  • What is the point of GetFullPath here? Doesn't Path.Combine already return the full path, or is this to auto-expand things like '..'? – Mark A. Donohoe Oct 14 '13 at 23:36
1

Use Path.GetDirectoryName() on the result of new Uri(Assembly.GetExecutingAssembly().CodeBase).AbsolutePath then Path.Combine() your relative path onto the end.

nitzmahone
  • 13,720
  • 2
  • 36
  • 39