public void CallbackForCompletedReadAtEndOfEmptyFile() { FileAsyncIOResult result; using (var io = new IOCompletionManager()) using (var target = new BlockingCompletionTarget(bufferSize: 10)) using ( SafeFileHandle handle = CreateOrOpenFile( GetFullPath("emptyFile"), FileDesiredAccess.GenericWrite | FileDesiredAccess.GenericRead, FileShare.Read | FileShare.Delete, FileMode.Create)) { io.BindFileHandle(handle); unsafe { io.ReadFileOverlapped(target, handle, target.PinBuffer(), target.Buffer.Length, fileOffset: 0); } result = target.Wait(); } XAssert.IsTrue(result.ErrorIndicatesEndOfFile, "File is empty; EOF read expected"); XAssert.AreEqual(FileAsyncIOStatus.Failed, result.Status); }
public void ReadFileToEnd() { const int NumberOfWords = 1024 * 1024; const int TotalSize = NumberOfWords * 4; string path = GetFullPath("file"); using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Delete)) using (var writer = new BinaryWriter(fs, Encoding.UTF8, leaveOpen: true)) { for (int i = 0; i < NumberOfWords; i++) { writer.Write((int)i); } } using (var memoryStream = new MemoryStream(capacity: NumberOfWords * 4)) { using (var io = new IOCompletionManager()) using (var target = new BlockingCompletionTarget(bufferSize: 64 * 1024)) using ( SafeFileHandle handle = CreateOrOpenFile( path, FileDesiredAccess.GenericRead, FileShare.Read | FileShare.Delete, FileMode.Open)) { io.BindFileHandle(handle); while (true) { unsafe { io.ReadFileOverlapped(target, handle, target.PinBuffer(), target.Buffer.Length, fileOffset: memoryStream.Length); } FileAsyncIOResult result = target.Wait(); if (result.Status == FileAsyncIOStatus.Failed) { XAssert.IsTrue(result.ErrorIndicatesEndOfFile, "Unexpected non-EOF read failure."); break; } else { XAssert.AreEqual(FileAsyncIOStatus.Succeeded, result.Status); } XAssert.AreNotEqual(0, result.BytesTransferred); XAssert.IsTrue( memoryStream.Length + result.BytesTransferred <= TotalSize, "Too many bytes read; Read {0} so far and just got another {1} bytes", memoryStream.Length, result.BytesTransferred); memoryStream.Write(target.Buffer, 0, result.BytesTransferred); } } memoryStream.Position = 0; using (var reader = new BinaryReader(memoryStream, Encoding.UTF8, leaveOpen: true)) { for (int i = 0; i < NumberOfWords; i++) { XAssert.AreEqual(i, reader.ReadInt32(), "File contents read incorrectly; offset {0}", i * 4); } } } }