Skip to content

Commit 1ca9b53

Browse files
Erik Renesfgreinacher
authored andcommitted
Verified FileShare behavior of File.Delete and implemented the same.
1 parent afe3609 commit 1ca9b53

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

System.IO.Abstractions.TestingHelpers.Tests/MockFileLockTests.cs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,5 +162,28 @@ public void MockFile_Lock_FileShareDeleteDoesNotThrowFileMove()
162162

163163
Assert.DoesNotThrow(() => filesystem.File.Move(filepath, target));
164164
}
165+
[Test]
166+
public void MockFile_Lock_FileShareNoneThrowsDelete()
167+
{
168+
string filepath = XFS.Path(@"c:\something\does\exist.txt");
169+
var filesystem = new MockFileSystem(new Dictionary<string, MockFileData>
170+
{
171+
{ filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.None }}
172+
});
173+
174+
var exception = Assert.Throws(typeof(IOException), () => filesystem.File.Delete(filepath));
175+
Assert.That(exception.Message, Is.EqualTo($"The process cannot access the file '{filepath}' because it is being used by another process."));
176+
}
177+
[Test]
178+
public void MockFile_Lock_FileShareDeleteDoesNotThrowDelete()
179+
{
180+
string filepath = XFS.Path(@"c:\something\does\exist.txt");
181+
var filesystem = new MockFileSystem(new Dictionary<string, MockFileData>
182+
{
183+
{ filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.Delete }}
184+
});
185+
186+
Assert.DoesNotThrow(() => filesystem.File.Delete(filepath));
187+
}
165188
}
166189
}

System.IO.Abstractions.TestingHelpers/MockFile.cs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,12 @@ public override void Delete(string path)
177177
// but silently returns if deleting a non-existing file in an existing folder.
178178
VerifyDirectoryExists(path);
179179

180+
var file = mockFileDataAccessor.GetFile(path);
181+
if (file != null && !file.AllowedFileShare.HasFlag(FileShare.Delete))
182+
{
183+
throw new IOException($"The process cannot access the file '{path}' because it is being used by another process.");
184+
}
185+
180186
mockFileDataAccessor.RemoveFile(path);
181187
}
182188

0 commit comments

Comments
 (0)