We have a C# application which will write files to a configurable location. The set of files (and relative paths) is determined at runtime.
We want to ensure that it cannot write files outside the configured location.
For example, the configured location might be c:\Stuff\Export, it would be an error for the program to write anything under C:\Stuff\Important
Really, I think we can achieve this in two ways:
1) Assert none of the relative paths (files to be written) specify ‘Parent directory’ (typically “../”) – System.Path doesn’t specify a “parent directory” path component though (like it has for path separation i.e. System.Path.PathSeparator). I feel a bit cludgey checking for “../” in the string.
2) Assert that all of the final absolute paths that are generated (by combining the output location with the file relative path) are relative to i.e. underneath the output location. I’m not exactly sure how to go about this though.
Example usage:
Output directory: c:\Stuff\Export
Output path 1: "foo\bar\important.xls"
Output path 2: "foo\boo\something.csv"
Output path 3: "../../io.sys"
Expected final files
1. c:\Stuff\Export\foo\bar\important.xls
2. c:\Stuff\Export\foo\boo\something.csv
3. Should throw exception
If you create a
DirectoryInfoinstance on the two paths, itsFullNameproperty should return the fully qualified, canonical path. So if you just do that for both of the sides you want to compare, you can do this:Since
FullNameis just a string, you can do regular string comparison on the paths, like:You can also use the
Parentproperty and compare itsFullNameto the chosen directory, if you don’t want to allow sub-directories within the configured directory: