1

I need to get file size in Windows kernel. I read the file into a buffer in kernel, while the code is as below. And I dig out a lot.

// 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] = '\0';
        //DbgPrint("%s\n", Buffer);
    }
    ZwClose(handle);
}

Someone suggested to use GetFileSize(), but my VS2019 reported below error:

    Severity    Code    Description Project File    Line    Suppression State
Error (active)  E0020   identifier "GetFileSize" is undefined   TabletAudioSample   D:\workspace\4\Windows-driver-samples\audio\sysvad\adapter.cpp  702

If I add the header file:

#include <fileapi.h>

Then I got another error reported:

    Severity    Code    Description Project File    Line    Suppression State
Error (active)  E1696   cannot open source file "fileapi.h" TabletAudioSample   D:\workspace\4\Windows-driver-samples\audio\sysvad\adapter.cpp  24  

Thanks!

1
  • 2
    you need ZwQueryInformationFile or NtQueryInformationFile (depend from previous mode) with FileStandardInformation Commented Jun 22, 2020 at 13:04

1 Answer 1

3

GetFileSize is not a WDK function. Use ZwQueryInformationFile instead of GetFileSize.

Use the codes below

    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.
    }

instead of ZwReadFile in your codes. And include <wdm.h>, not a <fileapi.h>.

The is all the same as RbMm commented, And I hope my example codes can help you too.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.