forked from TestableIO/System.IO.Abstractions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileHandles.cs
More file actions
56 lines (50 loc) · 1.73 KB
/
FileHandles.cs
File metadata and controls
56 lines (50 loc) · 1.73 KB
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
using System;
using System.Collections.Concurrent;
using System.IO;
using System.IO.Abstractions.TestingHelpers;
public class FileHandles
{
private readonly ConcurrentDictionary<string, ConcurrentDictionary<Guid, (FileAccess access, FileShare share)>> handles = new();
public void AddHandle(string path, Guid guid, FileAccess access, FileShare share)
{
var pathHandles = handles.GetOrAdd(
path,
_ => new ConcurrentDictionary<Guid, (FileAccess, FileShare)>());
var requiredShare = AccessToShare(access);
foreach (var (existingAccess, existingShare) in pathHandles.Values)
{
var existingRequiredShare = AccessToShare(existingAccess);
var existingBlocksNew = (existingShare & requiredShare) != requiredShare;
var newBlocksExisting = (share & existingRequiredShare) != existingRequiredShare;
if (existingBlocksNew || newBlocksExisting)
{
throw CommonExceptions.ProcessCannotAccessFileInUse(path);
}
}
pathHandles[guid] = (access, share);
}
public void RemoveHandle(string path, Guid guid)
{
if (handles.TryGetValue(path, out var pathHandles))
{
pathHandles.TryRemove(guid, out _);
if (pathHandles.IsEmpty)
{
handles.TryRemove(path, out _);
}
}
}
private static FileShare AccessToShare(FileAccess access)
{
var share = FileShare.None;
if (access.HasFlag(FileAccess.Read))
{
share |= FileShare.Read;
}
if (access.HasFlag(FileAccess.Write))
{
share |= FileShare.Write;
}
return share;
}
}