Even if you get the System.Type
from the string name of it, you only get it typed as object
and you can't call members defined on FileSystemSecurity
classes. You could use generics and pass a <T>
but still you will have to proceed with a bunch of reflection calls using strings which are plain ugly.
You can use rely on DLR using the dynamic
keyword, much less the hassle. Though it doesn't give the benefits of compile time error checking, dynamic
makes it much cleaner. At least you can see your code as it is.
public static void SetFileFolderPermissions(dynamic info)
{
if (!(info is FileInfo) || !(info is DirectoryInfo))
throw new explosion;
try
{
var security = info.GetAccessControl();
security.AddAccessRule(new FileSystemAccessRule(...));
info.SetAccessControl(security);
}
catch
{
Console.WriteLine("Error.");
}
}
You can pass either a FileInfo
object or DirectoryInfo
object. If your FileSystemAccessRule
vary for both, then you can either pass it as a parameter, or do if-else
check in the method to decide. To make your method more foolproof, you can make the method private and provide two public method overloads, like:
public static void SetFilePermissions(string path)
{
SetFileFolderPermissions
(
new FileInfo(path),
new FileSystemAccessRule
(
"TestAccount",
FileSystemRights.FullControl,
AccessControlType.Allow
)
);
}
//so that now nobody from outside can pass any dumb object to it
static void SetFileFolderPermissions(dynamic info, FileSystemAccessRule rule)
{
try
{
var security = info.GetAccessControl();
security.AddAccessRule(rule);
info.SetAccessControl(security);
}
catch
{
Console.WriteLine("Error.");
}
}
public static void SetFolderPermissions(string path)
{
SetFileFolderPermissions
(
new DirectoryInfo(path),
new FileSystemAccessRule
(
"TestAccount",
FileSystemRights.FullControl,
InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit,
PropagationFlags.NoPropagateInherit,
AccessControlType.Allow
)
);
}
Now you dont have to pass around the bulky access rules if its written once as a part of a method overload. But I would say its still not worth doing all this, given you lose compile time checking... Also avoid the try-catch they way you have used.