Skip to content

Instantly share code, notes, and snippets.

@bgavrilMS
Created March 21, 2022 15:55
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 bgavrilMS/1d23b419e78bbaf83bb29aca28a2e7b8 to your computer and use it in GitHub Desktop.
Save bgavrilMS/1d23b419e78bbaf83bb29aca28a2e7b8 to your computer and use it in GitHub Desktop.
CreateFileWithPermissions
Console.WriteLine("Hello World!");
//WellKnownSidType sid = WellKnownSidType.;
//FileSystemRights rights = FileSystemRights.FullControl;
//AccessControlType controlType = AccessControlType.Allow;
FileSecurity security = new FileSecurity();
var rights = FileSystemRights.Read | FileSystemRights.Write;
var adminIdentifier = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
security.AddAccessRule(
new FileSystemAccessRule(
adminIdentifier,
rights,
InheritanceFlags.None,
PropagationFlags.NoPropagateInherit,
AccessControlType.Allow));
security.AddAccessRule(
new FileSystemAccessRule(
WindowsIdentity.GetCurrent().Name,
rights,
InheritanceFlags.None,
PropagationFlags.NoPropagateInherit,
AccessControlType.Allow));
security.SetAccessRuleProtection(isProtected: true, preserveInheritance: false);
using (var directory = new TempDirectory())
{
using (var tempFile = new TempFile(Path.Combine("c:\\temp", "file.txt")))
{
FileInfo info = new FileInfo(tempFile.Path);
using (FileStream fs = info.Create(FileMode.Create, rights, FileShare.Read, DefaultBufferSize, FileOptions.None, security))
{
await fs.WriteAsync(Encoding.UTF8.GetBytes("Hello World 2!"));
}
string val = File.ReadAllText(tempFile.Path);
Console.WriteLine(val);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment