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?
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 .
string sourceFile = System. IO. Path. Combine(sourcePath, fileName);
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With