如何在Windows内核中获取文件大小

How to get file size in Windows kernel

本文关键字:获取 文件大小 内核 Windows      更新时间:2023-10-16

我需要在Windows内核中获取文件大小。我将文件读入内核中的缓冲区,而代码如下。我挖了很多。

// read file
//LARGE_INTEGER byteOffset;
ntstatus = ZwCreateFile(&handle,
GENERIC_READ,
&objAttr, &ioStatusBlock,
NULL,
FILE_ATTRIBUTE_NORMAL,
0,
FILE_OPEN,
FILE_SYNCHRONOUS_IO_NONALERT,
NULL, 0);
if (NT_SUCCESS(ntstatus)) {
byteOffset.LowPart = byteOffset.HighPart = 0;
ntstatus = ZwReadFile(handle, NULL, NULL, NULL, &ioStatusBlock,
Buffer, (ULONG)BufferLength, &byteOffset, NULL);
if (NT_SUCCESS(ntstatus)) {
//Buffer[BufferLength - 1] = '';
//DbgPrint("%sn", Buffer);
}
ZwClose(handle);
}

有人建议使用GetFileSize((,但我的VS2019报告了以下错误:

Severity    Code    Description Project File    Line    Suppression State
Error (active)  E0020   identifier "GetFileSize" is undefined   TabletAudioSample   D:workspace4Windows-driver-samplesaudiosysvadadapter.cpp  702

如果我添加头文件:

#include <fileapi.h>

然后我收到了另一个错误报告:

Severity    Code    Description Project File    Line    Suppression State
Error (active)  E1696   cannot open source file "fileapi.h" TabletAudioSample   D:workspace4Windows-driver-samplesaudiosysvadadapter.cpp  24  

谢谢!

GetFileSize 不是 WDK 函数。 使用 ZwQueryInformationFile 而不是 GetFileSize。

使用以下代码

FILE_STANDARD_INFORMATION fileInfo = {0};
ntStatus = ZwQueryInformationFile(
handle,
&ioStatusBlock,
&fileInfo,
sizeof(fileInfo),
FileStandardInformation
);
if (NT_SUCCESS(ntstatus)) {
//. fileInfo.EndOfFile is the file size of handle.
}

而不是代码中的 ZwReadFile。 并包括,而不是

这与 RbMm 评论的都一样,我希望我的示例代码也能为您提供帮助。