0

How can I prevent paths built with Path.Combine to end up being outside of a given root directory?

E.g.

string root = Path.Combine("/some", "dir");

string okay = Path.Combine(root, "sub");               // /some/dir/sub
string bad = Path.Combine(root, "sub/../../evil.exe"); // /evil.exe

Is there any functionality to easily ensure this while building paths? Or a built-in way to at least test it?

(I wouldn't be suprised if there is a duplicate question, but obviously I was unable to find the proper search terms. I would appreciate both answers and links to similar questions, thank you

dube
  • 4,898
  • 2
  • 23
  • 41
  • `Or a built-in way to at least test it` - [`Path.GetRelativePath`](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getrelativepath?view=net-6.0)? – GSerg Mar 28 '22 at 07:19
  • Thanks, kind stranger! `Path.GetFullPath(somePath).StartsWith(baseFolder)` indeed does the job – dube Mar 28 '22 at 14:09

0 Answers0