Win down drive file operation correlation function encapsulation

Source: Internet
Author: User
Tags strcmp

Create a file

Create file handle Kernelcreatefile (in punicode_string pstrfile,//File path symbolic link in BOOLEAN bisdir)//Is folder {H    Andle hfile = NULL;    NTSTATUS Status = status_unsuccessful;    Io_status_block Statusblock = {0}; ULONG ulshareaccess = File_share_read | File_share_write |    File_share_delete;    ULONG ulcreateopt = File_synchronous_io_nonalert; 1.    Initialize the contents of the object_attributes object_attributes Objattrib = {0}; ULONG ulattributes = obj_case_insensitive |    Obj_kernel_handle;  Initializeobjectattributes (&objattrib,//returns the initialized struct Pstrfile,//File object name Ulattributes,   object property NULL, or NULL); Generally null//2.        Create file Object ulcreateopt |= bisdir?    File_directory_file:file_non_directory_file; Status = ZwCreateFile (&hfile,//return file handle Generic_all,//File Operation description &obj Attrib,//ObjeCt_attributes &statusblock,//accept the operation result of the function 0,//initial file size File_attribute _normal,//New file Properties ulshareaccess,//File Share file_open_if,//file exists then open does not exist then create ulCreate                   OPT,//Open operation with additional flag bit NULL,//Extended attribute area 0); Extended attribute area length if (!    Nt_success (Status)) return (HANDLE)-1; return hfile;}

Get File size

//获取文件大小ULONG64 KernelGetFileSize(IN HANDLE hfile){    // 查询文件状态    IO_STATUS_BLOCK           StatusBlock = { 0 };    FILE_STANDARD_INFORMATION fsi = { 0 };    NTSTATUS Status = STATUS_UNSUCCESSFUL;    Status = ZwQueryInformationFile(        hfile,        // 文件句柄        &StatusBlock, // 接受函数的操作结果        &fsi,         // 根据最后一个参数的类型输出相关信息        sizeof(FILE_STANDARD_INFORMATION),        FileStandardInformation);    if (!NT_SUCCESS(Status))        return 0;    return fsi.EndOfFile.QuadPart;}

Read file

ULONG64 KernelReadFile(    IN  HANDLE         hfile,    // 文件句柄    IN  PLARGE_INTEGER Offset,   // 从哪里开始读取    IN  ULONG          ulLength, // 读取多少字节    OUT PVOID          pBuffer)  // 保存数据的缓存{    // 1. 读取文件    IO_STATUS_BLOCK StatusBlock = { 0 };    NTSTATUS        Status = STATUS_UNSUCCESSFUL;    Status = ZwReadFile(        hfile,        // 文件句柄        NULL,         // 信号状态(一般为NULL)        NULL, NULL,   // 保留        &StatusBlock, // 接受函数的操作结果        pBuffer,      // 保存读取数据的缓存        ulLength,     // 想要读取的长度        Offset,       // 读取的起始偏移        NULL);        // 一般为NULL    if (!NT_SUCCESS(Status))  return 0;    // 2. 返回实际读取的长度    return StatusBlock.Information;}

Write file

//写文件ULONG64 KernelWriteFile(    IN HANDLE         hfile,    // 文件句柄    IN PLARGE_INTEGER Offset,   // 从哪里开始写入    IN ULONG          ulLength, // 写入多少字节    IN PVOID          pBuffer)  // 欲写入的数据{    // 1. 写入文件    IO_STATUS_BLOCK StatusBlock = { 0 };    NTSTATUS        Status = STATUS_UNSUCCESSFUL;    Status = ZwWriteFile(        hfile,        // 文件句柄        NULL,         // 信号状态(一般为NULL)        NULL, NULL,   // 保留        &StatusBlock, // 接受函数的操作结果        pBuffer,      // 欲写入的数据        ulLength,     // 想要写入的长度        Offset,       // 写入的起始偏移        NULL);        // 一般为NULL    if (!NT_SUCCESS(Status))  return 0;    // 2. 返回实际写入的长度    // 2. 返回实际写入的长度    return StatusBlock.Information;}

deleting files

/删除文件NTSTATUS KernelDeleteFile(IN PUNICODE_STRING pstrFile){    // 1. 初始化OBJECT_ATTRIBUTES的内容    OBJECT_ATTRIBUTES objAttrib = { 0 };    ULONG             ulAttributes =        OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE;    InitializeObjectAttributes(        &objAttrib,    // 返回初始化完毕的结构体        pstrFile,      // 文件对象名称        ulAttributes,  // 对象属性        NULL,          // 根目录(一般为NULL)        NULL);         // 安全属性(一般为NULL)                       // 2. 删除指定文件/文件夹    return ZwDeleteFile(&objAttrib);}

Copy files

//拷贝文件VOID ZwMyCopyFile(    PUNICODE_STRING  SouPath,//源地址    PUNICODE_STRING DenPath  //目的地址){    //1 打开源地址文件    HANDLE hSorHandle = KernelCreateFile(SouPath, FALSE);    //2 获取大小    ULONG64 FileSize = KernelGetFileSize(hSorHandle);    //3 申请空间,读取数据    PVOID buf = ExAllocatePool(NonPagedPool, (SIZE_T)FileSize);    RtlZeroMemory(buf, (SIZE_T)FileSize);    LARGE_INTEGER Offset = {0,0};    KernelReadFile(hSorHandle, &Offset, (SIZE_T)FileSize, buf);    //4 打开目的地址文件    HANDLE hDenHandle = KernelCreateFile(DenPath, FALSE);    //5 写入数据    KernelWriteFile(hDenHandle, &Offset, (SIZE_T)FileSize, buf);    //6 关闭句柄    ZwClose(hSorHandle);    ZwClose(hDenHandle);}

File traversal

#define _COUNTOF (arr) sizeof (arr)/sizeof (arr[0]) BOOLEAN kernelfindfirstfile (in HANDLE hfile,//text                      Piece handle in ULONG Ullen,//Information length out pfile_both_dir_information pdir,//file information in ULONG                   Ufirstllen,//Information length out pfile_both_dir_information pfirstdir//First file information) {NTSTATUS    Status = status_unsuccessful;    Io_status_block Statusblock = {0}; 1. Gets the first file information to see if the success Status = Zwquerydirectoryfile (hfile, NULL, NULL, null,//file handle &statusblock,//Accept function Operation result Pfirstdir,//File information Ufirstllen,//"File information" data length filebothdirectoryinformation,//query            Mode TRUE,//whether to return a starting message null,//file handle pointing to the file (typically NULL) FALSE); Whether to start the first scan from the directory//2.    If successful, gets the file list if (nt_success (Status) = = False) {return false; } Status = Zwquerydirectoryfile (hfile, NULL, NULL, null,//file handle &statusblock,//Accept function operation result Pdir,//File information Ullen,//"File information" data length        Filebothdirectoryinformation,///Query mode FALSE,//whether to return a starting message null,//file handle pointing to the file (typically null)       FALSE); Whether to start the first scan from the directory return nt_success (Status);} BOOLEAN kernelfindnextfile (in pfile_both_dir_information pdirlist,//out pfile_both_dir_information pDirInfo, I N out LONG * Loc) {//If there is a next item, move the pointer to the next item pfile_both_dir_information Pdir = (pfile_both_dir_information) ((PCHAR) Pdirl    ist + *loc);    LONG structlenth = 0;        if (pdir->filename[0]! = 0) {structlenth = sizeof (file_both_dir_information);        memcpy (Pdirinfo, Pdir, Structlenth + pdir->filenamelength);        *loc = *loc + pdir->nextentryoffset;        if (Pdir->nextentryoffset = = 0) {*loc = *loc + structlenth + pdir->filenamelength;    } return TRUE; } return FALSE;} NTSTATUS Enmufile () {unicode_string Ustrfolder = {0}; WCHAR szsymbol[0x512] = L "\ \??"    \\";    Unicode_string Ustrpath = rtl_constant_string (L "c:\\");    HANDLE hfile = NULL;    size_t nfileinfosize = sizeof (file_both_dir_information) + * sizeof (WCHAR); size_t nSize = nfileinfosize * 0X256;    Assume a maximum of 0x256 files char strfilename[0x256] = {0};    Pfile_both_dir_information pfiletemp = NULL;    Pfile_both_dir_information pfilelist = NULL;    Pfilelist = (pfile_both_dir_information) exallocatepool (PagedPool, nSize);    Pfiletemp = (pfile_both_dir_information) exallocatepool (PagedPool, nfileinfosize); 1.    Assemble the path as a connection symbol name and open the file wcscat_s (Szsymbol, _countof (Szsymbol), ustrpath.buffer);    Rtlinitunicodestring (&ustrfolder, Szsymbol);    hfile = Kernelcreatefile (&ustrfolder, TRUE);        if (Kernelfindfirstfile (hfile, NSize, Pfilelist, Nfileinfosize, pfiletemp)) {LONG Loc = 0; do {rtlzeromemory (strFileName, 0x256);            Rtlcopymemory (strFileName, Pfiletemp->filename, Pfiletemp->filenamelength)            ;            if (strcmp (strFileName, ".") = = 0 | | strcmp (strFileName, ".") = = 0) continue; if (Pfiletemp->fileattributes & file_attribute_directory) dbgprint ("[Catalog]%s\n", Strfil            ENAME);            else Dbgprint ("[File]%s\n", strFileName);        memset (pfiletemp, 0, nfileinfosize);    } while (Kernelfindnextfile (Pfilelist, Pfiletemp, &loc)); } return status_success;}

Win down drive file operation related function encapsulation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.