tags:

views:

51

answers:

4

In .NET is there any API that allows me to restrict some IO operations to the specified path?

For example:

  • Root Path: C:\Test\

Now I want to call a function like this:

  • IO.Directory.CreateDirectory("../testing/",Root)

And now I want the API to handle this situation for me and do not create a folder other than the specified directory.

So this should be created as c:\Test\testing\ instead of c:\testing\.

I know I can manually do this but I thought maybe there is an API that I don't know which supports such a thing.

The thing is I've got bunch of random strings and I'll crate folders and files based on them, I don't want to write anything to another folder because one of these strings include a string like "../"

A: 

In *nix envoirnements thats called a chroot (jailroot). I'm not sure if there is something like this in .net, but you can try to google chroot for .net (or jailroot for .net).

Henri
chroot is a bit more like about permissions, I'm more after a simple API call which will take the canonicalization issues for me.
dr. evil
A: 

I found one:

DirectoryInfo.CreateSubdirectory()

not the exact same thing but similar, it checks if the given path is actually a subdirectory or not.

dr. evil
A: 

Other than using the DirectoryInfo class I'd suggest creating a simple extension method and using the Path.Combine static method.

// Extension Method
public static class DirectoryExtension
{
    public static void CreateDirectory(this DirectoryInfo root, string path)
    {
        if (!Directory.Exists(root.FullName))
        {
            Directory.CreateDirectory(root.FullName);
        }

        string combinedPath = Path.Combine(root.FullName, path);
        Directory.CreateDirectory(combinedPath);
    }
}

// Usage
DirectoryInfo root = new DirectoryInfo(@"c:\Test");
root.CreateDirectory("testing");
root.CreateDirectory("testing123");
root.CreateDirectory("testingabc");
root.CreateDirectory(@"abc\123");
Kane
Combine won't work in this though: Path.Combine("c:\test\", "\inroot") == "c:\inroot"
dr. evil
A: 

I don't know of any built-in .NET API to do what you want. I can't think of anything to do other than use Path.Combine() to combine the strings into a full path and then manually check to see if it is rooted where you want it.

CodeSavvyGeek