Home > Mobile >  Constraint a path to be within a folder
Constraint a path to be within a folder

Time:05-19

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.

CodePudding user response:

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.

CodePudding user response:

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

static void Main(string[] args)
{
    string folderRoot = @"F:\Projectes\Test\SourceGenerators";

    string fileName = @"..\..\..\..\Test1.sln";

    var fileInfo = new DirectoryInfo(fileName).Parent.GetFiles();

    Console.WriteLine((fileInfo[0].FullName.StartsWith(folderRoot)) ? "Match" : "Doesn't match");
}

As you can see, new DirectoryInfo(fileName).Parent.GetFiles(); 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:

FileInfo: F:\Projectes\Test\SourceGenerators\Test1\Test1.sln

Match
  • Related