ispiro
ispiro

Reputation: 27673

Constraint a path to be within a folder

Say you want to store a file within a folder C:\A\B\C and let the user supply the file name.

Just combine them, right?

Wrong.

If the user selects something like \..\..\Ha.txt you might be in for a surprise.

So how do we restrict the result to within C:\A\B\C? It's fine if it's within a subfolder, just not over it.

Upvotes: 0

Views: 231

Answers (2)

McNets
McNets

Reputation: 10807

I've used one of my test projects, it really doesn't matter:

Using c#10

internal class Program
{
    static void Main(string[] args)
    {
        string template = @"F:\Projectes\Test\SourceGenerators";
        string folder = @"..\..\..\..\Test1.sln";

        Console.WriteLine(MatchDirectoryStructure(template, folder) 
                          ? "Match" 
                          : "Doesn't match");
    }

    static bool MatchDirectoryStructure(string template, string folder) 
        => new DirectoryInfo(folder).FullName.StartsWith(template);
}

As you can see, new DirectoryInfo(fileName).FullName; returns the real name of the directory.

From here you can check if it match with the desired result.

In this case the returned value is:

Match

Upvotes: 1

gunr2171
gunr2171

Reputation: 17520

If you're asking for a file name, then it should be just the name of the file. The more control you give to the user about subdirectories, the more they can mess with you.


The idea here is to split your path by both possible slashes (/ and \) and see if the value of any of the entries in the array is ...

string input = @"\..\..\Ha.txt";
bool containsBadSegments = input
    .Split(new [] { '/', '\\' })
    .Any(s => s is "..");

This answer only takes care of detecting \..\ in the path. There are plenty of other ways to input bad values, such as characters not allowed by the OS's file system, or absolute or rooted paths.

Upvotes: 1

Related Questions