Skip to content
Prev Previous commit
Next Next commit
ensure file does not exist after allocation fails
  • Loading branch information
adamsitnik committed Apr 13, 2021
commit 071fc3357d0a14e86b42ac01a1fe19b9047a5623
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public async Task FileOffsetIsPreservedWhenFileStreamIsCreatedFromSafeFileHandle

using FileStream createdFromHandle = new FileStream(stream.SafeFileHandle, FileAccess.Write);

Assert.Equal(buffer.Length, stream.Position);
Assert.Equal(buffer.Length, stream.Position);
Assert.Equal(stream.Position, createdFromHandle.Position);
}

Expand Down Expand Up @@ -187,17 +187,22 @@ public async Task WriteByteFlushesTheBufferWhenItBecomesFull()
byte[] allBytes = File.ReadAllBytes(filePath);
Assert.Equal(writtenBytes.ToArray(), allBytes);
}

[Fact]
public void WhenFileStreamFailsToPreallocateDiskSpaceTheErrorMessageContainsAllTheDetails()
{
const long tooMuch = 1024L * 1024L * 1024L * 1024L; // 1 TB

string filePath = GetTestFilePath();
IOException ex = Assert.Throws<IOException>(() => new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, BufferSize, Options, tooMuch));

Assert.False(File.Exists(filePath));

IOException ex = Assert.Throws<IOException>(() => new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None, BufferSize, Options, tooMuch));
Assert.Contains("disk was full", ex.Message);
Assert.Contains(filePath, ex.Message);
Assert.Contains(AllocationSize.ToString(), ex.Message);

Assert.False(File.Exists(filePath));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ internal static SafeFileHandle OpenHandle(string path, FileMode mode, FileAccess

// Open the file and store the safe handle.
SafeFileHandle handle = SafeFileHandle.Open(path!, openFlags, (int)OpenPermissions);
if (allocationSize > 0 && (mode == FileMode.Create || mode == FileMode.CreateNew || mode == FileMode.Truncate))
if (allocationSize > 0 && (mode == FileMode.Create || mode == FileMode.CreateNew || mode == FileMode.Truncate || mode == FileMode.OpenOrCreate))
{
int allocationResult = Interop.Sys.FAllocate(handle, 0, allocationSize);

Expand Down