Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining a DirectoryInfo and a FileInfo path

Tags:

.net

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?
like image 352
Dimitri C. Avatar asked Jan 08 '10 10:01

Dimitri C.


People also ask

How path combine works?

The combined paths. If one of the specified paths is a zero-length string, this method returns the other path. If path2 contains an absolute path, this method returns path2 .

How to concatenate file path in c#?

string sourceFile = System. IO. Path. Combine(sourcePath, fileName);

Why we use path combine?

Path. Combine uses the Path. PathSeparator and it checks whether the first path has already a separator at the end so it will not duplicate the separators. Additionally, it checks whether the path elements to combine have invalid chars.

Which property of the system IO DirectoryInfo class can be used to get the full path of the directory?

Gets the name of this DirectoryInfo instance. This Name property returns only the name of the directory, such as "Bin." To get the full path, such as "c:\public\Bin", use the FileSystemInfo. FullName property.


2 Answers

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)); 

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

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

The OriginalPath property can not be access directly because of the "protected" statuts.

like image 198
Alfred Myers Avatar answered Sep 27 '22 02:09

Alfred Myers


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.

like image 22
Oliver Friedrich Avatar answered Sep 23 '22 02:09

Oliver Friedrich