Skip to content

Instantly share code, notes, and snippets.

@superlucky8848
Last active January 12, 2016 11:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save superlucky8848/747a7d24e16e65c26e54 to your computer and use it in GitHub Desktop.
Save superlucky8848/747a7d24e16e65c26e54 to your computer and use it in GitHub Desktop.
(C# Windows) Check if a file path (relative or absolute) can be written by current user without attempting to create open or actually write anything to it. Inspired by http://stackoverflow.com/questions/1281620/checking-for-directory-and-file-write-permissions-in-net
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;
private bool FileCanWrite(string path)
{
bool writeAllow = false;
bool writeDeny = false;
try
{
FileSystemSecurity security;
if (File.Exists(path)) security = File.GetAccessControl(path);
else security = Directory.GetAccessControl(Path.GetDirectoryName(Path.GetFullPath(path)));
AuthorizationRuleCollection rules = security.GetAccessRules(true, true, typeof(NTAccount));
WindowsPrincipal curUser = new WindowsPrincipal(WindowsIdentity.GetCurrent());
foreach (FileSystemAccessRule rule in rules)
{
if (0 == (rule.FileSystemRights & (FileSystemRights.Write | FileSystemRights.WriteData))) continue;
if (rule.IdentityReference.Value.StartsWith("S-1-"))
{
SecurityIdentifier sid = new SecurityIdentifier(rule.IdentityReference.Value);
if (!curUser.IsInRole(sid)) continue;
}
else if (!curUser.IsInRole(rule.IdentityReference.Value)) continue;
if (rule.AccessControlType == AccessControlType.Deny) writeDeny = true;
else if (rule.AccessControlType == AccessControlType.Allow) writeAllow = true;
}
}
catch
{
writeDeny = true;
}
return writeAllow && !writeDeny;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment