Copying a file!

Please discuss general Delphi programming topics here.

Copying a file!

Postby SaeedShekari » August 25th, 2010, 7:55 am

Hi all :)

I am trying to copy a file (any) from Windows\System32\Draivers using a Windows API function:
CopyFile('C:\Windows\System32\drivers\1394bus.sys', 'c:\1394bus.sys', False);
But it is not working,
The same function works for any other file from any folder.
Do I need to set any access privilege?

Any suggestion or help is appreciated.
Thnaks
Saeed Shekari

This code can set the access privilege for a few purposes; I tried calling this function with different parameters before copying, but all failed.
Code: Select all
Function SetAccessPrivilege(Const PrivilegeStr : String; State : Integer):Integer;
Var
  hToken : THandle;
  aluid : TLargeInteger;
  cbPrevTP : DWORD;
  tp, fPrevTP : PTokenPrivileges;
Begin
  result := 0;
  If OpenProcessToken (GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES Or
      TOKEN_QUERY, hToken) Then
  Try
    LookupPrivilegeValue (Nil, PChar (PrivilegeStr), aluid);
    cbPrevTP := SizeOf (TTokenPrivileges) + sizeof (TLUIDAndAttributes);
    GetMem (tp, cbPrevTP);
    GetMem (fPrevTP, cbPrevTP);
    Try
      tp^.PrivilegeCount := 1;
      tp^.Privileges [0].Luid := aLuid;
      tp^.Privileges [0].Attributes := State;
      If Not AdjustTokenPrivileges (hToken, False, tp^, cbPrevTP, fPrevTP^, cbPrevTP) Then
        RaiseLastWin32Error;
      Result := fPrevTP^.Privileges [0].Attributes;
    Finally
      FreeMem (fPrevTP);
      FreeMem (tp);
    End
  Finally
   CloseHandle (hToken);
  End
End;

// Example for calling above function
//
// Procedure ChangeDateTime( SysDateTime: SYSTEMTIME);
// Begin
//   SetAccessPrivilege('wbemPrivilegeSystemtime',SE_PRIVILEGE_ENABLED);
//   SetLocalTime(SysDateTime);
// End;

// Function BackupRegistry(R: TRegistry; RegKey, FileName: String): Boolean;
// Begin
//   SetAccessPrivilege('SeBackupPrivilege', SE_PRIVILEGE_ENABLED);
//   Result:= R.SaveKey(RegKey, FileName);
// End;

(*
ACCESS PRIVILEDGE FOR NT
 wbemPrivilegeCreateToken Required to create a primary token.

SeAssignPrimaryTokenPrivilege
2 wbemPrivilegePrimaryToken Required to assign the primary token of a process.

SeLockMemoryPrivilege
3 wbemPrivilegeLockMemory Required to lock physical pages in memory.

SeIncreaseQuotaPrivilege
4 wbemPrivilegeIncreaseQuota Required to increase the quota assigned to a process.

SeMachineAccountPrivilege
5 wbemPrivilegeMachineAccount Required to create a computer account.

SeTcbPrivilege
6 wbemPrivilegeTcb Identifies its holder as part of the trusted computer base. Some trusted, protected subsystems
are granted this privilege.

SeSecurityPrivilege
7 wbemPrivilegeSecurity Required to perform a number of security-related functions, such as controlling and
viewing audit messages. This privilege identifies its holder as a security operator.

SeTakeOwnershipPrivilege
8 wbemPrivilegeTakeOwnership Required to take ownership of an object without being granted discretionary access.
This privilege allows the owner value to be set only to those values that the holder may legitimately assign as
the owner of an object.

SeLoadDriverPrivilege
9 wbemPrivilegeLoadDriver Required to load or unload a device driver.

SeSystemProfilePrivilege
10 wbemPrivilegeSystemProfile Required to gather profiling information for the entire system.

SeSystemtimePrivilege
11 wbemPrivilegeSystemtime Required to modify the system time.

SeProfileSingleProcessPrivilege
12 wbemPrivilegeProfileSingleProcess Required to gather profiling information for a single process.

SeIncreaseBasePriorityPrivilege
13 wbemPrivilegeIncreaseBasePriority Required to increase the base priority of a process.

SeCreatePagefilePrivilege
14 wbemPrivilegeCreatePagefile Required to create a paging file.

SeCreatePermanentPrivilege
15 wbemPrivilegeCreatePermanent Required to create a permanent object.

SeBackupPrivilege
16 wbemPrivilegeBackup Required to perform backup operations.

SeRestorePrivilege
17 wbemPrivilegeRestore Required to perform restore operations. This privilege enables you to set any valid user
or group SID as the owner of an object.

SeShutdownPrivilege
18 wbemPrivilegeShutdown Required to shut down a local system.

SeDebugPrivilege
19 wbemPrivilegeDebug Required to debug a process.

SeAuditPrivilege
20 wbemPrivilegeAudit Required to generate audit-log entries.

SeSystemEnvironmentPrivilege
21 wbemPrivilegeSystemEnvironment
Required to modify the nonvolatile RAM of systems that use this type of memory
to store configuration information.

SeChangeNotifyPrivilege
22 wbemPrivilegeChangeNotify Required to receive notifications of changes to files or directories.
This privilege also causes the system to skip all traversal access checks. It is enabled by default for all users.

SeRemoteShutdownPrivilege
23 wbemPrivilegeRemoteShutdown Required to shut down a system using a network request.

SeUndockPrivilege
24 wbemPrivilegeUndock Required to remove computer from docking station.

SeSyncAgentPrivilege
25 wbemPrivilegeSyncAgent Required to synchronize directory service data.

SeEnableDelegationPrivilege
26 wbemPrivilegeEnableDelegation Required to enable computer and user accounts to be trusted for delegation.

*)
Saeed Shekari
User avatar
SaeedShekari
Active Member
Active Member
 
Posts: 20
Joined: March 8th, 2008, 2:01 pm
Location: UAE

Re: Copying a file!

Postby Kambiz » August 26th, 2010, 7:34 am

I checked it out.

Even when the application is ran with the administrator privilege, it can't see the file.

Couldn't find a solution, sorry!
Kambiz
User avatar
Kambiz
Administrator
Administrator
 
Posts: 2429
Joined: March 7th, 2003, 7:10 pm

Re: Copying a file!

Postby SaeedShekari » August 26th, 2010, 5:29 pm

Hi Kambiz,

It seems accessing those sys files in System32\Drivers folder through an EXE needs something we do not know! I even used a TOpenDialog with *.* filter and when it is opening it does not show those sys files in there! This is while those sys files are fully accessible within Explorer! I can even remove them without getting any error message!
Anyhow, thanks for spending your time on checking this issue.
Saeed Shekari
User avatar
SaeedShekari
Active Member
Active Member
 
Posts: 20
Joined: March 8th, 2008, 2:01 pm
Location: UAE

Re: Copying a file!

Postby geowink » August 26th, 2010, 5:37 pm

I answered this but it never showed up. Try again. I use Delphi 6. I did the Copy function and it worked perfectly. I used a different name for the copied file and it showed up just fine.

George
George
geowink
Junior Member
Junior Member
 
Posts: 37
Joined: November 29th, 2005, 3:59 am
Location: La Grange, Illinois

Re: Copying a file!

Postby Kambiz » August 26th, 2010, 8:05 pm

George,

What is version of your Windows? I think you've an XP, right?
Kambiz
User avatar
Kambiz
Administrator
Administrator
 
Posts: 2429
Joined: March 7th, 2003, 7:10 pm

Re: Copying a file!

Postby geowink » August 26th, 2010, 9:48 pm

Yes, I have XP. I guess Windows 7 does everything it can to screw a user. Pathetic.

George
George
geowink
Junior Member
Junior Member
 
Posts: 37
Joined: November 29th, 2005, 3:59 am
Location: La Grange, Illinois

Re: Copying a file!

Postby SaeedShekari » August 27th, 2010, 8:25 am

Hi George and Kambiz,

I am using Windows 7 Ultimate 64 bit, I did not try this in Win XP.
I tried Delphi 5, 7, and 2010, and C++ Builder 6 and 2010 but the result was the same.
After George’s first comment, I tried a bit more and I got different results!

This is the code I used:
CopyFile(WinSysPath + '\drivers\aksclass.sys' , 'C:\', 0);

I also tried this:
CopyFile(WinSysPath + '\drivers\aksclass.sys' , 'C:\ aksclass.sys ', 0);

This SYS file may not exist in your computer, but the result was the same for other sys files in that folder, if I try the same code for copying any file from any other folder, it works all fine.

I noticed it may copy but randomly and a few times I saw it was showing this below message and created an empty folder if I was clicking on ‘YES’! The message on a dialog was like this:

‘The C:\ aksclass.sys folder does not exist. The file might have been moved or deleted.’
‘Do you want to create it?’
‘YES(button) SKIP CANCEL’

Any action with those sys files in System32\Drivers folder is possible in Explorer, I can Copy/Rename or even remove a sys file!

I tried changing the ownership of the file and allowing all kind of actions on the file, but yet it did not work. :(
I also tried to create a BAT file at runtime and tred to call that, but it also failed! The same BAT file was working fine when I was running it within the Explorer. It looks something is required to force Windows to unlock those files for an EXE file, I also tried changing Access Privilege, it did not work either!
Saeed Shekari
User avatar
SaeedShekari
Active Member
Active Member
 
Posts: 20
Joined: March 8th, 2008, 2:01 pm
Location: UAE

Re: Copying a file!

Postby Athabasca » August 28th, 2010, 9:34 am

...use the shell function to copy/move a file?

http://www.swissdelphicenter.ch/en/showcode.php?id=28
User avatar
Athabasca
Active Member
Active Member
 
Posts: 15
Joined: January 30th, 2009, 10:55 am
Location: Germany

Re: Copying a file!

Postby SaeedShekari » August 28th, 2010, 7:04 pm

Hi Athabasca :)

Thanks for the link, I tried it,
This new API function (SHFileOperation) has the same problem as I explained in my erlier post!

SHFileOperation and CopyFile in Windows XP SP3 with Delphi 5 displayed below error message when copying a file from Windows\System32\Drivers to C:\
Image

The same function in Windows 7 Ultimate 64bit with Delphi 5 displayed another message and created an empty folder! No files were copied!
ShellFileOperation('C:\Windows\System32\drivers\aksclass.sys', 'C:\aksclass.sys', FO_COPY);
(it thinks the source file is a folder!)
Image

And Delphi 2010 in same Win 7, showed the same result as Delphi 5, (an empty folder was created) but it did not display any message!
Image

And sometimes calling these two API functions looks to have no effects, no message no empty folder! nothing happens!
Strangely any action is possible on these files through Explorer!
Saeed Shekari
User avatar
SaeedShekari
Active Member
Active Member
 
Posts: 20
Joined: March 8th, 2008, 2:01 pm
Location: UAE

Re: Copying a file!

Postby Athabasca » August 30th, 2010, 4:50 am

Hi SaeedShekari,

this code works fine...

(Windows XP SP3; Delphi 2006)

Code: Select all
uses
ShellApi;

function CopyFileEx(const ASource, ADest: string;
ARenameCheck: boolean = false): boolean;
var
  sh: TSHFileOpStruct;
begin
  sh.Wnd := Application.Handle;
  sh.wFunc := FO_COPY;

  // Terminated string must be to put the list end with # 0 # 0
  sh.pFrom := PChar(ASource + #0);
  sh.pTo := PChar(ADest + #0);
  sh.fFlags := fof_Silent or fof_MultiDestFiles;
  if ARenameCheck then
    sh.fFlags := sh.fFlags or fof_RenameOnCollision;
  Result:=ShFileOperation(sh)=0;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  CopyFileEx('C:\Windows\System32\drivers\aksclass.sys', 'C:\aksclass.sys');
end;
User avatar
Athabasca
Active Member
Active Member
 
Posts: 15
Joined: January 30th, 2009, 10:55 am
Location: Germany

Re: Copying a file!

Postby SaeedShekari » September 1st, 2010, 4:17 am

Hi Athabasca,
Thanks for your help. The problem is accessing those sys files in System32\drivers folder. SHFileOperation did not work either.

Below function works like all those other copy functions, but it also fails in those sys files!
(all these functions can work for other files! Only those sys files in that Drivers folder look to have this issue!)
Code: Select all
Function MyCopyFile(Src, Dest: String): Boolean;
 Type
   TManyBytes = Packed Array[1..2000000] Of Byte;
Var
  hFile: THandle;
  Size, ReadSize: Cardinal;
  S: String;
  F: TFileStream;
  Ptr: ^TManyBytes;
Begin

  hFile:= CreateFile(PChar(Src),
                     GENERIC_READ,
                     FILE_SHARE_READ,
                     Nil,
                     OPEN_EXISTING,
                     FILE_ATTRIBUTE_SYSTEM OR FILE_ATTRIBUTE_OFFLINE,
                     0);
  Size:= GetFileSize (hFile, Nil);
  If Size = -1 Then
  Begin
    FormatMessage(
      FORMAT_MESSAGE_ALLOCATE_BUFFER Or
      FORMAT_MESSAGE_FROM_SYSTEM Or
      FORMAT_MESSAGE_IGNORE_INSERTS,
      Nil, GetLastError(), 0, @S, 0, Nil );
    Application.MessageBox(PChar(S), 'Error!', MB_OK);
    Result:= False;
    Exit;
  End;

  GetMem(Ptr, Size);
  ReadFile(hFile, Ptr^, Size, ReadSize, Nil);
  F:= TFileStream.Create(Dest, fmCreate);
  F.Write(Ptr^, Size);
  F.Free;
  FreeMem(Ptr);
  CloseHandle(hFile);
  Result:= True;
End;
Saeed Shekari
User avatar
SaeedShekari
Active Member
Active Member
 
Posts: 20
Joined: March 8th, 2008, 2:01 pm
Location: UAE

Re: Copying a file!

Postby Athabasca » September 1st, 2010, 10:58 am

Probably not have the administrator rights.
User avatar
Athabasca
Active Member
Active Member
 
Posts: 15
Joined: January 30th, 2009, 10:55 am
Location: Germany


Return to Delphi Programming

Who is online

Users browsing this forum: No registered users and 12 guests

cron