O'Reilly logo

Programming C# 4.0 by Jesse Liberty, Matthew Adams, Ian Griffiths

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Creating and Securing Directory Hierarchies

Directory.CreateDirectory is very straightforward: it does exactly what its name suggests. In fact, it will create any directories in the whole path that do not already exist, so you can create a deep hierarchy with a single call. (You’ll notice that Example 11-14 didn’t bother to create the Programming CSharp\FindDuplicates folder—those will get created automatically the first time we run as a result of creating the temporary folders inside them.) A side effect of this is that it is safe to call it if all of the directories in the path already exist—it will just do nothing.

In addition to the overload we’ve used, there’s a second which also takes a DirectorySecurity parameter:

Directory.CreateDirectory(string path, DirectorySecurity directorySecurity)

The DirectorySecurity class allows you to specify filesystem access controls with a relatively simple programming model. If you’ve tried using the Win32 ACL APIs, you’ll know that it is a nightmare of GUIDs, SSIDs, and lists sensitive to item ordering. This model does away with much of the complexity.

Let’s extend our create function to make sure that only our current user has read/write/modify permissions on these directories. Example 11-15 modifies the previous example by explicitly granting the current user full control of the newly created folders. The new or changed lines are highlighted.

Example 11-15. Configuring access control on new directories

private static string[] MakeTestDirectories() ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required