Last active
January 12, 2016 11:30
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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