Parsi Coders
Native File Read And Write Example - نسخه قابل چاپ

+- Parsi Coders (http://parsicoders.com)
+-- انجمن: Software Development Programming (http://parsicoders.com/forumdisplay.php?fid=37)
+--- انجمن: Pascal/Delphi (http://parsicoders.com/forumdisplay.php?fid=45)
+---- انجمن: Delphi (http://parsicoders.com/forumdisplay.php?fid=69)
+---- موضوع: Native File Read And Write Example (/showthread.php?tid=1293)



Native File Read And Write Example - Amin_Mansouri - 11-27-2011

کد:
AnsiToFile: function for write ansistring value to file use native api
FileToAnsi: function for read file to ansistring use native api

کد:
function AnsiToFile(wsFileName: WideString; Buff:AnsiString):Boolean;
var
  hFile:  THANDLE;
  Oa:     TObjectAttributes;
  Us:     TUnicodeString;
  iosb:   IO_STATUS_BLOCK;
  st:     NTSTATUS;
begin
  result := false;
  RtlDosPathNameToNtPathName_U(@wsFileName[1], Us, nil, nil);
  InitializeObjectAttributes(@Oa, @Us, $40, 0, nil);

  {Create file}
  st := NtCreateFile(
    @hFile,
    FILE_WRITE_DATA or SYNCHRONIZE,
    @oa,
    @iosb,
    nil,
    0,
    FILE_SHARE_READ,
    FILE_CREATE,
    FILE_SYNCHRONOUS_IO_NONALERT,
    nil,
    0
  );
  if st <> STATUS_SUCCESS then exit;

  {WriteBuff}
  NtWriteFile(
    hFile,
    0,
    nil,
    nil,
    @iosb,
    @Buff[1],
    length(Buff),
    nil,
    nil
  );

  NtClose(hFile);
end;

function FileToAnsi(wsFileName: WideString):AnsiString;
var
  hFile:  THANDLE;
  Oa:     TObjectAttributes;
  Us:     TUnicodeString;
  iosb:   IO_STATUS_BLOCK;
  fsi:    FILE_STANDARD_INFORMATION;
  st:     NTSTATUS;
  fsize:  Cardinal;
begin
  result := '';
  RtlDosPathNameToNtPathName_U(@wsFileName[1], Us, nil, nil);
  InitializeObjectAttributes(@Oa, @Us, $40, 0, nil);

  {open file}
  st := NtOpenFile(
    @hFile,
    FILE_READ_DATA or SYNCHRONIZE,
    @oa,
    @iosb,
    FILE_SHARE_READ,
    FILE_SYNCHRONOUS_IO_NONALERT
  );
  if st <> STATUS_SUCCESS then exit;

  {Query Information File}
  st := NtQueryInformationFile(
    hFile,
    @iosb,
    @fsi,
    Sizeof(FILE_STANDARD_INFORMATION),
    FileStandardInformation//FileStandardInformation
  );
  if st <> STATUS_SUCCESS then begin
    NtClose(hFile);
    exit;
  end;

  {Get FileSize}
  fsize := fsi.EndOfFile.LowPart;
  Setlength(result, fsize);

  {ReadFile}
  NtReadFile(
    hFile,
    0,
    nil,
    nil,
    @iosb,
    @result[1],
    fsize,
    nil,
    nil
  );

  NtClose(hFile);

end;

example:
Code:
کد:
var
  buff:ansistring;
begin
  buff := FileToAnsi(paramstr(0));
  AnsiToFile('test.exe', buff);
end.