我正在使用 C# 直接从磁盘读取并调用 kernel32 ReadFile 方法。我注意到,对于较大的读取(当前仅读取单个块),缓冲区大小超出范围。
有谁知道这里读取缓冲区的最大大小?
如果是这样,当我有多余的内存要读入时限制缓冲区大小的目的是什么?我了解缓冲和保持小内存占用的概念,但为什么要强制我们使用小尺寸?也许只是旧 Win32 API 的产物?
编辑:收到的错误Marshal.GetLastWin32Error()
是“值不在预期范围内”。
我收到此错误之前的上限是 8192 字节(8KB - 因此我很困惑)。
using System;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
namespace DiskRead
{
class Program
{
public const uint GenericRead = 0x80000000;
public const uint FileShareRead = 1;
public const uint FileShareWrite = 2;
public const uint OpenExisting = 3;
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern IntPtr CreateFile(string lpFileName, uint dwDesiredAccess,
uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition,
uint dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool ReadFile(IntPtr hFile, [Out] byte[] lpBuffer,
uint nNumberOfBytesToRead, out uint lpNumberOfBytesRead, IntPtr lpOverlapped);
static void Main(string[] args)
{
string path = @"\\.\PhysicalDrive0";
IntPtr ptr = CreateFile(path, GenericRead, FileShareRead | FileShareWrite, IntPtr.Zero, OpenExisting, 0, IntPtr.Zero);
SafeFileHandle handleValue = new SafeFileHandle(ptr, true);
FileStream fileStream = new FileStream(handleValue, FileAccess.Read);
const uint numberOfBytesToRead = 8193;
uint bytesRead;
byte[] buffer = new byte[numberOfBytesToRead];
if (!ReadFile(handleValue.DangerousGetHandle(), buffer, numberOfBytesToRead, out bytesRead, IntPtr.Zero))
{
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
}
}
}
提前致谢。