-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
TempAclDirectory.cs
79 lines (70 loc) · 3.2 KB
/
TempAclDirectory.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Security.AccessControl;
using System.Security.Principal;
namespace System.IO
{
/// <summary>
/// Represents a temporary directory.
/// Disposing will recurse all files and directories inside it, ensure the
/// appropriate access control is set, then delete all of them.
/// </summary>
public sealed class TempAclDirectory : TempDirectory
{
internal readonly List<DirectoryInfo> CreatedSubdirectories = new();
internal readonly List<FileInfo> CreatedSubfiles = new();
public TempAclDirectory([CallerMemberName] string memberName = null, [CallerLineNumber] int lineNumber = 0)
: base(IO.Path.Combine(IO.Path.GetTempPath(), PathGenerator.GenerateTestFileName(null, memberName, lineNumber)))
{
}
/// <summary>
/// the returned path can be used both as directory and as file name
/// </summary>
public string GenerateSubItemPath([CallerMemberName] string memberName = null, [CallerLineNumber] int lineNumber = 0)
=> IO.Path.Combine(Path, PathGenerator.GenerateTestFileName(null, memberName, lineNumber));
protected override void DeleteDirectory()
{
try
{
foreach (DirectoryInfo subdir in CreatedSubdirectories)
{
ResetFullControlToDirectory(subdir);
}
foreach (FileInfo subfile in CreatedSubfiles)
{
ResetFullControlToFile(subfile);
}
var rootDirInfo = new DirectoryInfo(Path);
ResetFullControlToDirectory(rootDirInfo);
rootDirInfo.Delete(recursive: true);
}
catch { /* Do not throw because we call this on finalize */ }
}
private void ResetFullControlToDirectory(DirectoryInfo dirInfo)
{
try
{
var identity = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
var accessRule = new FileSystemAccessRule(identity, FileSystemRights.FullControl, AccessControlType.Allow);
var security = new DirectorySecurity(dirInfo.FullName, AccessControlSections.Access);
security.AddAccessRule(accessRule);
dirInfo.SetAccessControl(security);
}
catch { /* Skip silently if dir does not exist */ }
}
private void ResetFullControlToFile(FileInfo fileInfo)
{
try
{
var identity = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
var accessRule = new FileSystemAccessRule(identity, FileSystemRights.FullControl, AccessControlType.Allow);
var security = new FileSecurity(fileInfo.FullName, AccessControlSections.Access);
security.AddAccessRule(accessRule);
fileInfo.SetAccessControl(security);
}
catch { /* Skip silently if file does not exist */ }
}
}
}