Delphi的移动文件方法,转/删除文件:/文件的复制

RenameFile,DeleteFile,MoveFile

Delphi的移动文件方法

uses

ShellApi;

procedure ShellFileOperation(fromFile: string; toFile: string; Flags: Integer);

var

shellinfo: TSHFileOpStructA;

begin

with shellinfo do

begin

wnd := Application.Handle;

wFunc := Flags;

pFrom := PChar(fromFile);

pTo := PChar(toFile);

end;

SHFileOperation(shellinfo);

end;

// Example, Beispiel:

procedure TForm1.Button1Click(Sender: TObject);

begin

ShellFileOperation('c:\afile.txt', 'd:\afile2.txt', FO_COPY);

// To Move a file: FO_MOVE

end;

该方法的另一种表示:

function TScanFileThread.MoveFile(FileName: string): Boolean;
var
  F: TShFileOpStruct;
begin
  with F do begin
    Wnd := Handle;
    wFunc := FO_MOVE;
    pFrom := PChar(Directory + FileName + #0#0);
    pTo := PChar(SaveDirectory + FileName + #0#0);
    fFlags := FOF_RENAMEONCOLLISION or FOF_NOCONFIRMMKDIR;
  end;
  if ShFileOperation(F) = 0 then begin
    Result := True;
  end
  else begin
    Result := False;
  end;
end;

一开始pFrom和pTo没有以“#0#0”结尾,结果发现在有的机器上能移动成功,有的机器上SHFileOperation返回1026无法转移,查了一下资料

ShFileOperation中的pFrom和pTo中可以包含多个文件名,文件名之间用 '\0' 分割,最后以两个\0结束。

/////////////////////////////////////////////////////////////////////////

1、

CopyFile(PChar(源目录),PChar(目标目录),True);

CopyFileTo('F:\MyProject\delphi\message\data\data.mdb','c:\data.mdb');//不能覆盖已存在的文件******//

//***************下面的这个WINAPI最后的一个参数为true时不覆盖已经存在的文件。为false时自动覆盖存在的文件。*********//

//***************

CopyFile(pchar(''+MyPath+'/data/data.mdb'),pchar(''+MyPath+'/data/backup.mdb'),false);

2、

api的不会

我一般是在程序中根据程序所在目录建立一个批处理文件

copy x:\xxx\xxx.exe c:;

exit;

在窗体创建或退出时执行;

因为在外地网吧,所以不能提供代码,不过这个应该不难。

3、

也可以直接调用shellexec winexec,

shellexec('copy gp.exe c:')

4、

不用api的如下:

procedure CopyFile (SourceName, TargetName: String);

var

Stream1, Stream2: TFileStream;

begin

Stream1 := TFileStream.Create (SourceName, fmOpenRead);

try

Stream2 := TFileStream.Create (TargetName, fmOpenWrite or fmCreate);

try

Stream2.CopyFrom (Stream1, Stream1.Size);

finally

Stream2.Free;

end

finally

Stream1.Free;

end

end;

5、

如果是在本程序运行的时候复制本程序的话,可以这样:

procedure Tform1.formCreate(Sender: TObject);

var

s:Pchar;

begin

s:= Pchar(Application.ExeName);

copyfile(s, 'c:\a.exe', true);

end;

6、

CopyFile(PChar(源文件),PChar(目标文件),True);为False表示覆盖

7、

才看到这个贴子,可以用以下的方法:

CopyFile(pchar('c:\sql.txt'), pchar('d:\sql.txt'), True);

只要是文件的复制,都可以。

移动文件:

MoveFile(pchar('c:\sql.txt'), pchar('d:\sql.txt'));

删除文件:

DeleteFile('c:\sql.txt');

以上都是可行的。