Home  |  Delphi .net Home  |  System.IO.File  |  Copy Method
Copy  
Method  
Copies the specified file to a new location, optionally with a new name
File Class
System.IO NameSpace
CF1.  Procedure Copy ( SourceFileName:StringSourceFileName : String; TargetFileName : String; ) ;
CF2.  Procedure Copy ( SourceFileName:StringSourceFileName : String; TargetFileName : String; OverWrite : Boolean; ) ; Static;
CF : Methods with this mark are Compact Framework Compatible
Description
The SourceFileName file is copied to the new TargetFileName.
 
If the file already exists, an exception is thrown unless the optional Overwrite is set to true.
Microsoft MSDN Links
System.IO
System.IO.File
 
 
A simple example
program Project1;
{$APPTYPE CONSOLE}

uses
  System.IO;

var
  Path   : String;
  Files  : Array of String;
  Stream : FileStream;
  i      : Integer;

begin
  // Create the DelphiBasics.txt file
  Path := 'C:\DelphiBasics.txt';
  Stream := System.IO.File.&Create(Path);

  // Close the file
  Stream.Close;

  // List files in the current folder
  Files := System.IO.Directory.GetFiles(Directory.GetCurrentDirectory);

  for i := 0 to Length(Files)-1 do
    Console.WriteLine(System.IO.Path.GetFileName(Files[i]));

  // Copy the file to a new file
  Console.WriteLine;
  Console.WriteLine('Copy DelphiBasics.txt to CopyOfDelphiBasics.txt :');
  Console.WriteLine;

  System.IO.File.Copy(Path, 'CopyOfDelphiBasics.txt');

  // List files in the current folder
  Files := System.IO.Directory.GetFiles(Directory.GetCurrentDirectory);

  for i := 0 to Length(Files)-1 do
    Console.WriteLine(System.IO.Path.GetFileName(Files[i]));

  // Clean up - delete the new file
  System.IO.File.Delete('CopyOfDelphiBasics.txt');

  Console.Readline;
end.
Show full unit code
  DelphiBasics.txt
  Project1.exe
  Project1.pdb
  Project1.rsp
  
  Copy DelphiBasics.txt to CopyOfDelphiBasics.txt
  
  CopyOfDelphiBasics.txt
  DelphiBasics.txt
  Project1.exe
  Project1.pdb
  Project1.rsp
 
 
Delphi Programming © Neil Moffatt All rights reserved.  |  Contact the author