Restricting file/folder write to paths other then the specified root
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 thou开发者_Python百科ght 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 "../"
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).
I found one:
DirectoryInfo.CreateSubdirectory()
not the exact same thing but similar, it checks if the given path is actually a subdirectory or not.
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");
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.
精彩评论