Skip to content

Commit 4392421

Browse files
authored
Open file via FileStream with ReadWrite sharing (#743)
* Open file via FileStream with ReadWrite sharing Replace File.OpenText(path) with a FileStream using FileMode.Open, FileAccess.Read and FileShare.ReadWrite, then wrap it in a StreamReader. This allows reading files that may be concurrently written to by other processes while preserving the existing Read(...) behavior. * Update Directory.Build.props
1 parent 03e6596 commit 4392421

4 files changed

Lines changed: 37 additions & 3 deletions

File tree

src/Directory.Build.props

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
<Project>
33
<PropertyGroup>
44
<NoWarn>CS1591;NU1608;NU1109</NoWarn>
5-
<Version>28.0.1</Version>
5+
<Version>28.0.2</Version>
66
<LangVersion>preview</LangVersion>
77
<AssemblyVersion>1.0.0</AssemblyVersion>
88
<PackageTags>Markdown, Snippets, mdsnippets, documentation, MarkdownSnippets</PackageTags>
@@ -16,4 +16,4 @@
1616
<ItemGroup>
1717
<Using Include="System.ReadOnlySpan&lt;System.Char&gt;" Alias="CharSpan" />
1818
</ItemGroup>
19-
</Project>
19+
</Project>

src/MarkdownSnippets/Reading/FileSnippetExtractor.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,8 @@ public static IEnumerable<Snippet> Read(string path, int maxWidth = int.MaxValue
101101
return [];
102102
}
103103

104-
using var reader = File.OpenText(path);
104+
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
105+
using var reader = new StreamReader(stream);
105106
return Read(reader, path, maxWidth, newLine).ToList();
106107
}
107108

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
[
2+
{
3+
Key: CodeKey,
4+
Language: cs,
5+
Value: The Code,
6+
Error: ,
7+
FileLocation: LockedFile.cs(1-3),
8+
IsInError: false
9+
}
10+
]

src/Tests/SnippetExtractor/SnippetExtractorTests.cs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,29 @@ await Verify(snippets)
3939
}
4040
}
4141

42+
[Fact]
43+
public Task CanReadFileWhileLockedByAnotherProcess()
44+
{
45+
var temp = Path.Combine(Path.GetTempPath(), "LockedSnippetFile.cs");
46+
try
47+
{
48+
File.WriteAllText(temp,
49+
"""
50+
#region CodeKey
51+
The Code
52+
#endregion
53+
""");
54+
using var lockingStream = new FileStream(temp, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
55+
var snippets = FileSnippetExtractor.Read(temp);
56+
return Verify(snippets)
57+
.AddScrubber(_ => _.Replace(temp, "LockedFile.cs"));
58+
}
59+
finally
60+
{
61+
File.Delete(temp);
62+
}
63+
}
64+
4265
[Fact]
4366
public Task CanExtractWithInnerWhiteSpace()
4467
{

0 commit comments

Comments
 (0)