tags:

views:

268

answers:

4

If I have an absolute DirectoryInfo path and a relative FileInfo path, how can I combine them into an absolute FileInfo path?

For example:

var absoluteDir = new DirectoryInfo(@"c:\dir");
var relativeFile = new FileInfo(@"subdir\file");
var absoluteFile = new FileInfo(absoluteDir, relativeFile); //-> How to get this done?
+1  A: 

Try this:

Path.Combine(absolute, relative);
Rubens Farias
+1  A: 

Path.Combine?

Joe
Does this work with DirectoryInfo and FileInfo, or only with strings?
Dimitri C.
Only strings; can't you to work with `dir.FullName` or `file.FullName`?
Rubens Farias
A: 

You can just use the FullPath Property on FileInfo class.

FileInfo.FullPath Will get you the full qualified path, whereas

FileInfo.OriginalPath will give you the specified relative path.

If you just wish to combine to different pathes, e.g. the file you want to add the relative path to anoter path, then you should use Path.Combine() for this, as stated already.

BeowulfOF
+1  A: 

If absoluteDir and relativeFile exist for the sole purpose of being used to create absoluteFile, use should probably stick with plain strings for them and leaving only absoluteFile as a FileInfo.

var absoluteDir = @"c:\dir"; 
var relativeFile = @"subdir\file"; 
var absoluteFile = new FileInfo(Path.Combine(absoluteDir, relativeFile)); 

If otherwise you really need them to be typed, then you should use Path.Combine applied to the OriginalPath of each of them, such as in:

var absoluteDir = new DirectoryInfo(@"c:\dir"); 
var relativeFile = new FileInfo(@"subdir\file"); 
var absoluteFile = new FileInfo(Path.Combine(absoluteDir.OriginalPath), relativeFile.OriginalPath)); 
Alfred Myers
Thanks! So aparently, there is no real class for encapsulating a file system path in the .NET class library. By the way: don't you miss such a class?
Dimitri C.
I don't miss a class, but maybe a constructor overload that accepts two or more FileSystemInfo (the base class of both FileInfo and DirectoryInfo) or strings using params. The constructor would then combine them all.
Alfred Myers