Tschareck
Tschareck

Reputation: 4239

Possible reason of Path.Combine omitting one of parameters

I noticed that my code writes files to incorrect folders, so I added some logging and the result amazes me. My code:

 string savePath = Path.Combine(mapping.Folder, fileMeta.RelativePath, fileMeta.Filename);
 logger.Info(mapping.Folder);
 logger.Info(fileMeta.RelativePath);
 logger.Info(fileMeta.Filename);
 logger.Info("savepath: {0}", savePath);

This is, what has been written to log:

C:\Sync
\0100_MACHINES
Layout US.pdf 
savepath: \0100_MACHINES\Layout US.pdf

Can anyone give possible reason, why Path.Combine omits first argument, and just combines second and third? What is also funny, that happened only on one machine.

Upvotes: 5

Views: 1197

Answers (2)

bottaio
bottaio

Reputation: 5073

If path2 does not include a root (for example, if path2 does not start with a separator character or a drive specification), the result is a concatenation of the two paths, with an intervening separator character. If path2 includes a root, path2 is returned. https://msdn.microsoft.com/en-us/library/dd784047(v=vs.110).aspx

Seems like C# is treating relative folder as root path, thus ignoring path1.

Upvotes: 2

Tschareck
Tschareck

Reputation: 4239

Second parameter starts with backslash character. This caused Path.Combine to omit the part before. Solved this problem by adding TrimStart:

string savePath = Path.Combine(mapping.Folder, 
                     fileMeta.RelativePath.TrimStart('\\'), 
                     fileMeta.Filename.TrimStart('\\'));

Upvotes: 10

Related Questions