Skip to content

Commit b3a6212

Browse files
committed
Fix length caching
1 parent 84502ff commit b3a6212

1 file changed

Lines changed: 9 additions & 4 deletions

File tree

src/libraries/System.Private.CoreLib/src/System/IO/Strategies/OSFileStreamStrategy.cs

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ internal abstract class OSFileStreamStrategy : FileStreamStrategy
1717

1818
protected long _filePosition;
1919
private long _appendStart; // When appending, prevent overwriting file.
20-
private long _length = -1; // When the file is locked for writes (_share <= FileShare.Read) cache file length in-memory, negative means that hasn't been fetched.
20+
private long _length = -1; // When the file is locked for writes on Windows (_share <= FileShare.Read) cache file length in-memory, negative means that hasn't been fetched.
2121
private bool _exposedHandle; // created from handle, or SafeFileHandle was used and the handle got exposed
2222

2323
internal OSFileStreamStrategy(SafeFileHandle handle, FileAccess access, FileShare share)
@@ -84,7 +84,7 @@ public unsafe sealed override long Length
8484
{
8585
get
8686
{
87-
if (!OperatingSystem.IsWindows() || _share > FileShare.Read || _exposedHandle)
87+
if (!LengthCachingSupported)
8888
{
8989
return RandomAccess.GetFileLength(_fileHandle);
9090
}
@@ -105,7 +105,7 @@ protected void UpdateLengthOnChangePosition()
105105
{
106106
// Do not update the cached length if the file is not locked
107107
// or if the length hasn't been fetched.
108-
if (!OperatingSystem.IsWindows() || _share > FileShare.Read || _length < 0 || _exposedHandle)
108+
if (!LengthCachingSupported || _length < 0)
109109
{
110110
Debug.Assert(_length < 0);
111111
return;
@@ -117,6 +117,8 @@ protected void UpdateLengthOnChangePosition()
117117
}
118118
}
119119

120+
private bool LengthCachingSupported => OperatingSystem.IsWindows() && _share <= FileShare.Read && !_exposedHandle;
121+
120122
/// <summary>Gets or sets the position within the current stream</summary>
121123
public sealed override long Position
122124
{
@@ -235,7 +237,10 @@ protected unsafe void SetLengthCore(long value)
235237
Debug.Assert(value >= 0, "value >= 0");
236238

237239
FileStreamHelpers.SetFileLength(_fileHandle, value);
238-
_length = value;
240+
if (LengthCachingSupported)
241+
{
242+
_length = value;
243+
}
239244

240245
if (_filePosition > value)
241246
{

0 commit comments

Comments
 (0)