Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
2739e85
fix: added correct handling of file share in file stream constructor/…
HarrisonTCodes Oct 18, 2025
ec701cf
fix: added stateful tracking of unshared file streams and prevented m…
HarrisonTCodes Oct 18, 2025
2a70ae1
refactor: changed fileshare none streams state to use concurrent dict…
HarrisonTCodes Oct 30, 2025
18716e4
refactor: used existing common exception for file-in-use error in fil…
HarrisonTCodes Oct 30, 2025
c660094
feat: added handling of failed addition of exclusive file stream to t…
HarrisonTCodes Oct 30, 2025
d648b5e
chore: explicit API acceptance test changes
HarrisonTCodes Oct 31, 2025
9952eab
test: added exclusive mock file stream handling unit tests
HarrisonTCodes Oct 31, 2025
4e724f5
feat: added path normalization to mock file stream
HarrisonTCodes Oct 31, 2025
c9e04a2
fix: improved path normalization in mock file stream for relative paths
HarrisonTCodes Oct 31, 2025
f241cc2
fix: added improved handling of file stream options in factory method
HarrisonTCodes Nov 9, 2025
eabc64e
refactor: de-duplicated normalize/fix path logic moving method to pat…
HarrisonTCodes Nov 9, 2025
2db45c1
chore: explicit API acceptance test changes to cover path verifier ch…
HarrisonTCodes Nov 9, 2025
611907b
feat: added more rigorous tracking of open file streams and shares/ac…
HarrisonTCodes Nov 13, 2025
cd2a151
feat: moved open file handles state to mock file system and ran API a…
HarrisonTCodes Nov 14, 2025
fd3062a
feat: added proper checking of access and share on file stream constr…
HarrisonTCodes Nov 14, 2025
543acdb
test: added unit tests to cover simultaneous file stream opening with…
HarrisonTCodes Nov 14, 2025
795891b
fix: used explicit GUID call instead of target-typed new for clarity …
HarrisonTCodes Nov 14, 2025
42a7402
Merge branch 'main' into fix/file-stream-sharing
HarrisonTCodes Nov 14, 2025
c689d74
chore: explicit API acceptance test changes for dotnet version 10
HarrisonTCodes Nov 14, 2025
8b23795
refactor: made path verifier fix path method internal
HarrisonTCodes Nov 16, 2025
a61e568
feat: added file handles class and updated mock file system/stream to…
HarrisonTCodes Nov 17, 2025
15ed8d6
refactor: renamed add handle method on file handles class
HarrisonTCodes Nov 20, 2025
9a2d277
Merge branch 'main' into fix/file-stream-sharing
vbreuss Nov 21, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -110,4 +110,9 @@ public interface IMockFileDataAccessor : IFileSystem
/// Gets a reference to the underlying file system.
/// </summary>
IFileSystem FileSystem { get; }

/// <summary>
/// Gets a reference to the open file handles.
/// </summary>
FileHandles FileHandles { get; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -677,7 +677,7 @@ private FileSystemStream OpenInternal(
}
mockFileDataAccessor.AdjustTimes(mockFileData, timeAdjustments);

return new MockFileStream(mockFileDataAccessor, path, mode, access, options);
return new MockFileStream(mockFileDataAccessor, path, mode, access, FileShare.Read, options);
}

/// <inheritdoc />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ public NullFileSystemStream() : base(Null, ".", true)

private readonly IMockFileDataAccessor mockFileDataAccessor;
private readonly string path;
private readonly Guid guid = Guid.NewGuid();
private readonly FileAccess access = FileAccess.ReadWrite;
private readonly FileShare share = FileShare.Read;
private readonly FileOptions options;
private readonly MockFileData fileData;
private bool disposed;
Expand All @@ -42,6 +44,7 @@ public MockFileStream(
string path,
FileMode mode,
FileAccess access = FileAccess.ReadWrite,
FileShare share = FileShare.Read,
FileOptions options = FileOptions.None)
: base(new MemoryStream(),
path == null ? null : Path.GetFullPath(path),
Expand All @@ -51,6 +54,7 @@ public MockFileStream(
ThrowIfInvalidModeAccess(mode, access);

this.mockFileDataAccessor = mockFileDataAccessor ?? throw new ArgumentNullException(nameof(mockFileDataAccessor));
path = mockFileDataAccessor.PathVerifier.FixPath(path);
this.path = path;
this.options = options;

Expand Down Expand Up @@ -97,7 +101,9 @@ public MockFileStream(
mockFileDataAccessor.AddFile(path, fileData);
}

mockFileDataAccessor.FileHandles.AddHandle(path, guid, access, share);
this.access = access;
this.share = share;
}

private static void ThrowIfInvalidModeAccess(FileMode mode, FileAccess access)
Expand Down Expand Up @@ -144,6 +150,7 @@ protected override void Dispose(bool disposing)
{
return;
}
mockFileDataAccessor.FileHandles.RemoveHandle(path, guid);
InternalFlush();
base.Dispose(disposing);
OnClose();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,25 +41,25 @@ public FileSystemStream New(string path, FileMode mode, FileAccess access)

/// <inheritdoc />
public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share)
=> new MockFileStream(mockFileSystem, path, mode, access);
=> new MockFileStream(mockFileSystem, path, mode, access, share);

/// <inheritdoc />
public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize)
=> new MockFileStream(mockFileSystem, path, mode, access);
=> new MockFileStream(mockFileSystem, path, mode, access, share);

/// <inheritdoc />
public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync)
=> new MockFileStream(mockFileSystem, path, mode, access);
=> new MockFileStream(mockFileSystem, path, mode, access, share);

/// <inheritdoc />
public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize,
FileOptions options)
=> new MockFileStream(mockFileSystem, path, mode, access, options);
=> new MockFileStream(mockFileSystem, path, mode, access, share, options);

#if FEATURE_FILESTREAM_OPTIONS
/// <inheritdoc />
public FileSystemStream New(string path, FileStreamOptions options)
=> new MockFileStream(mockFileSystem, path, options.Mode, options.Access, options.Options);
=> new MockFileStream(mockFileSystem, path, options.Mode, options.Access, options.Share, options.Options);
#endif

/// <inheritdoc />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ public class MockFileSystem : FileSystemBase, IMockFileDataAccessor
private readonly PathVerifier pathVerifier;
#if FEATURE_SERIALIZABLE
[NonSerialized]
#endif
private readonly FileHandles fileHandles = new();
#if FEATURE_SERIALIZABLE
[NonSerialized]
#endif
private Func<DateTime> dateTimeProvider = defaultDateTimeProvider;
private static Func<DateTime> defaultDateTimeProvider = () => DateTime.UtcNow;
Expand Down Expand Up @@ -114,6 +118,8 @@ public MockFileSystem(IDictionary<string, MockFileData> files, MockFileSystemOpt
public IFileSystem FileSystem => this;
/// <inheritdoc />
public PathVerifier PathVerifier => pathVerifier;
/// <inheritdoc />
public FileHandles FileHandles => fileHandles;

/// <summary>
/// Replaces the time provider with a mocked instance. This allows to influence the used time in tests.
Expand All @@ -128,19 +134,6 @@ public MockFileSystem MockTime(Func<DateTime> dateTimeProvider)
return this;
}

private string FixPath(string path, bool checkCaps = false)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path), StringResources.Manager.GetString("VALUE_CANNOT_BE_NULL"));
}

var pathSeparatorFixed = path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
var fullPath = Path.GetFullPath(pathSeparatorFixed);

return checkCaps ? GetPathWithCorrectDirectoryCapitalization(fullPath) : fullPath;
}

//If C:\foo exists, ensures that trying to save a file to "C:\FOO\file.txt" instead saves it to "C:\foo\file.txt".
private string GetPathWithCorrectDirectoryCapitalization(string fullPath)
{
Expand Down Expand Up @@ -194,7 +187,7 @@ public MockFileData AdjustTimes(MockFileData fileData, TimeAdjustments timeAdjus
/// <inheritdoc />
public MockFileData GetFile(string path)
{
path = FixPath(path).TrimSlashes();
path = pathVerifier.FixPath(path).TrimSlashes();
return GetFileWithoutFixingPath(path);
}

Expand All @@ -210,7 +203,9 @@ public MockDriveData GetDrive(string name)

private void SetEntry(string path, MockFileData mockFile)
{
path = FixPath(path, true).TrimSlashes();
path = GetPathWithCorrectDirectoryCapitalization(
pathVerifier.FixPath(path)
).TrimSlashes();

lock (files)
{
Expand All @@ -232,7 +227,9 @@ private void SetEntry(string path, MockFileData mockFile)
/// <inheritdoc />
public void AddFile(string path, MockFileData mockFile, bool verifyAccess = true)
{
var fixedPath = FixPath(path, true);
var fixedPath = GetPathWithCorrectDirectoryCapitalization(
pathVerifier.FixPath(path)
);

mockFile ??= new MockFileData(string.Empty);
var file = GetFile(fixedPath);
Expand Down Expand Up @@ -319,7 +316,9 @@ public MockFileData GetFile(IFileInfo path)
/// <inheritdoc />
public void AddDirectory(string path)
{
var fixedPath = FixPath(path, true);
var fixedPath = GetPathWithCorrectDirectoryCapitalization(
pathVerifier.FixPath(path)
);
var separator = Path.DirectorySeparatorChar.ToString();

if (FileExists(fixedPath) && FileIsReadOnly(fixedPath))
Expand Down Expand Up @@ -408,8 +407,8 @@ public void AddDrive(string name, MockDriveData mockDrive)
/// <inheritdoc />
public void MoveDirectory(string sourcePath, string destPath)
{
sourcePath = FixPath(sourcePath);
destPath = FixPath(destPath);
sourcePath = pathVerifier.FixPath(sourcePath);
destPath = pathVerifier.FixPath(destPath);

var sourcePathSequence = sourcePath.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);

Expand Down Expand Up @@ -452,7 +451,7 @@ bool PathStartsWith(string path, string[] minMatch)
/// <inheritdoc />
public void RemoveFile(string path, bool verifyAccess = true)
{
path = FixPath(path);
path = pathVerifier.FixPath(path);

lock (files)
{
Expand All @@ -473,7 +472,7 @@ public bool FileExists(string path)
return false;
}

path = FixPath(path).TrimSlashes();
path = pathVerifier.FixPath(path).TrimSlashes();

lock (files)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -183,4 +183,23 @@ public bool TryNormalizeDriveName(string name, out string result)
result = name;
return true;
}

/// <summary>
/// Resolves and normalizes a path.
/// </summary>
internal string FixPath(string path)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path), StringResources.Manager.GetString("VALUE_CANNOT_BE_NULL"));
}

var pathSeparatorFixed = path.Replace(
_mockFileDataAccessor.Path.AltDirectorySeparatorChar,
_mockFileDataAccessor.Path.DirectorySeparatorChar
);
var fullPath = _mockFileDataAccessor.Path.GetFullPath(pathSeparatorFixed);

return fullPath;
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
[assembly: System.Reflection.AssemblyMetadata("RepositoryUrl", "https://github.com/TestableIO/System.IO.Abstractions.git")]
[assembly: System.Runtime.Versioning.TargetFramework(".NETCoreApp,Version=v10.0", FrameworkDisplayName=".NET 10.0")]
public class FileHandles
{
public FileHandles() { }
public void AddHandle(string path, System.Guid guid, System.IO.FileAccess access, System.IO.FileShare share) { }
public void RemoveHandle(string path, System.Guid guid) { }
}
namespace System.IO.Abstractions.TestingHelpers
{
public interface IMockFileDataAccessor : System.IO.Abstractions.IFileSystem
Expand All @@ -8,6 +14,7 @@ namespace System.IO.Abstractions.TestingHelpers
System.Collections.Generic.IEnumerable<string> AllDrives { get; }
System.Collections.Generic.IEnumerable<string> AllFiles { get; }
System.Collections.Generic.IEnumerable<string> AllPaths { get; }
FileHandles FileHandles { get; }
System.IO.Abstractions.IFileSystem FileSystem { get; }
System.IO.Abstractions.TestingHelpers.PathVerifier PathVerifier { get; }
System.IO.Abstractions.TestingHelpers.StringOperations StringOperations { get; }
Expand Down Expand Up @@ -384,7 +391,7 @@ namespace System.IO.Abstractions.TestingHelpers
[System.Serializable]
public class MockFileStream : System.IO.Abstractions.FileSystemStream, System.IO.Abstractions.IFileSystemAclSupport
{
public MockFileStream(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string path, System.IO.FileMode mode, System.IO.FileAccess access = 3, System.IO.FileOptions options = 0) { }
public MockFileStream(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string path, System.IO.FileMode mode, System.IO.FileAccess access = 3, System.IO.FileShare share = 1, System.IO.FileOptions options = 0) { }
public override bool CanRead { get; }
public override bool CanWrite { get; }
public static System.IO.Abstractions.FileSystemStream Null { get; }
Expand Down Expand Up @@ -440,6 +447,7 @@ namespace System.IO.Abstractions.TestingHelpers
public override System.IO.Abstractions.IDirectoryInfoFactory DirectoryInfo { get; }
public override System.IO.Abstractions.IDriveInfoFactory DriveInfo { get; }
public override System.IO.Abstractions.IFile File { get; }
public FileHandles FileHandles { get; }
public override System.IO.Abstractions.IFileInfoFactory FileInfo { get; }
public override System.IO.Abstractions.IFileStreamFactory FileStream { get; }
public System.IO.Abstractions.IFileSystem FileSystem { get; }
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
[assembly: System.Reflection.AssemblyMetadata("RepositoryUrl", "https://github.com/TestableIO/System.IO.Abstractions.git")]
[assembly: System.Runtime.Versioning.TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName=".NET Framework 4.7.2")]
public class FileHandles
{
public FileHandles() { }
public void AddHandle(string path, System.Guid guid, System.IO.FileAccess access, System.IO.FileShare share) { }
public void RemoveHandle(string path, System.Guid guid) { }
}
namespace System.IO.Abstractions.TestingHelpers
{
public interface IMockFileDataAccessor : System.IO.Abstractions.IFileSystem
Expand All @@ -8,6 +14,7 @@ namespace System.IO.Abstractions.TestingHelpers
System.Collections.Generic.IEnumerable<string> AllDrives { get; }
System.Collections.Generic.IEnumerable<string> AllFiles { get; }
System.Collections.Generic.IEnumerable<string> AllPaths { get; }
FileHandles FileHandles { get; }
System.IO.Abstractions.IFileSystem FileSystem { get; }
System.IO.Abstractions.TestingHelpers.PathVerifier PathVerifier { get; }
System.IO.Abstractions.TestingHelpers.StringOperations StringOperations { get; }
Expand Down Expand Up @@ -297,7 +304,7 @@ namespace System.IO.Abstractions.TestingHelpers
[System.Serializable]
public class MockFileStream : System.IO.Abstractions.FileSystemStream, System.IO.Abstractions.IFileSystemAclSupport
{
public MockFileStream(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string path, System.IO.FileMode mode, System.IO.FileAccess access = 3, System.IO.FileOptions options = 0) { }
public MockFileStream(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string path, System.IO.FileMode mode, System.IO.FileAccess access = 3, System.IO.FileShare share = 1, System.IO.FileOptions options = 0) { }
public override bool CanRead { get; }
public override bool CanWrite { get; }
public static System.IO.Abstractions.FileSystemStream Null { get; }
Expand Down Expand Up @@ -347,6 +354,7 @@ namespace System.IO.Abstractions.TestingHelpers
public override System.IO.Abstractions.IDirectoryInfoFactory DirectoryInfo { get; }
public override System.IO.Abstractions.IDriveInfoFactory DriveInfo { get; }
public override System.IO.Abstractions.IFile File { get; }
public FileHandles FileHandles { get; }
public override System.IO.Abstractions.IFileInfoFactory FileInfo { get; }
public override System.IO.Abstractions.IFileStreamFactory FileStream { get; }
public System.IO.Abstractions.IFileSystem FileSystem { get; }
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
[assembly: System.Reflection.AssemblyMetadata("RepositoryUrl", "https://github.com/TestableIO/System.IO.Abstractions.git")]
[assembly: System.Runtime.Versioning.TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName=".NET 6.0")]
public class FileHandles
{
public FileHandles() { }
public void AddHandle(string path, System.Guid guid, System.IO.FileAccess access, System.IO.FileShare share) { }
public void RemoveHandle(string path, System.Guid guid) { }
}
namespace System.IO.Abstractions.TestingHelpers
{
public interface IMockFileDataAccessor : System.IO.Abstractions.IFileSystem
Expand All @@ -8,6 +14,7 @@ namespace System.IO.Abstractions.TestingHelpers
System.Collections.Generic.IEnumerable<string> AllDrives { get; }
System.Collections.Generic.IEnumerable<string> AllFiles { get; }
System.Collections.Generic.IEnumerable<string> AllPaths { get; }
FileHandles FileHandles { get; }
System.IO.Abstractions.IFileSystem FileSystem { get; }
System.IO.Abstractions.TestingHelpers.PathVerifier PathVerifier { get; }
System.IO.Abstractions.TestingHelpers.StringOperations StringOperations { get; }
Expand Down Expand Up @@ -346,7 +353,7 @@ namespace System.IO.Abstractions.TestingHelpers
[System.Serializable]
public class MockFileStream : System.IO.Abstractions.FileSystemStream, System.IO.Abstractions.IFileSystemAclSupport
{
public MockFileStream(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string path, System.IO.FileMode mode, System.IO.FileAccess access = 3, System.IO.FileOptions options = 0) { }
public MockFileStream(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string path, System.IO.FileMode mode, System.IO.FileAccess access = 3, System.IO.FileShare share = 1, System.IO.FileOptions options = 0) { }
public override bool CanRead { get; }
public override bool CanWrite { get; }
public static System.IO.Abstractions.FileSystemStream Null { get; }
Expand Down Expand Up @@ -402,6 +409,7 @@ namespace System.IO.Abstractions.TestingHelpers
public override System.IO.Abstractions.IDirectoryInfoFactory DirectoryInfo { get; }
public override System.IO.Abstractions.IDriveInfoFactory DriveInfo { get; }
public override System.IO.Abstractions.IFile File { get; }
public FileHandles FileHandles { get; }
public override System.IO.Abstractions.IFileInfoFactory FileInfo { get; }
public override System.IO.Abstractions.IFileStreamFactory FileStream { get; }
public System.IO.Abstractions.IFileSystem FileSystem { get; }
Expand Down
Loading