FileInfo.CopyTo 方法

定義

複製現有的檔案到新的檔案。

多載

CopyTo(String)

複製現有的檔案到新的檔案,不允許覆寫現有的檔案。

CopyTo(String, Boolean)

複製現有的檔案到新檔案,允許覆寫現有的檔案。

CopyTo(String)

來源:
FileInfo.cs
來源:
FileInfo.cs
來源:
FileInfo.cs

複製現有的檔案到新的檔案,不允許覆寫現有的檔案。

public:
 System::IO::FileInfo ^ CopyTo(System::String ^ destFileName);
public System.IO.FileInfo CopyTo (string destFileName);
member this.CopyTo : string -> System.IO.FileInfo
Public Function CopyTo (destFileName As String) As FileInfo

參數

destFileName
String

要複製的目標新檔案名稱。

傳回

有完整路徑的新檔案。

例外狀況

.NET Framework和 2.1 之前的 .NET Core 版本: destFileName 是空的、只包含空白字元,或包含不正確字元。

發生錯誤,或者目的檔案已經存在。

呼叫端沒有必要的權限。

destFileNamenull

傳入了目錄路徑,或者檔案正要移至不同的磁碟機。

destFileName 中指定的目錄不存在。

指定的路徑、檔案名稱,或兩者都超出系統定義的長度上限。

字串內的 destFileName 包含冒號 (:),但未指定磁碟區。

範例

下列範例示範 方法的兩個 CopyTo 多載。

using namespace System;
using namespace System::IO;

int main()
{
   String^ path = "c:\\MyTest.txt";
   String^ path2 = "c:\\MyTest.txttemp";
   FileInfo^ fi1 = gcnew FileInfo( path );
   FileInfo^ fi2 = gcnew FileInfo( path2 );
   try
   {
      // Create the file and clean up handles.
      FileStream^ fs = fi1->Create();
      if ( fs )
         delete (IDisposable^)fs;
      
      //Ensure that the target does not exist.
      fi2->Delete();
      
      //Copy the file.
      fi1->CopyTo( path2 );
      Console::WriteLine( "{0} was copied to {1}.", path, path2 );
      
      //Try to copy it again, which should succeed.
      fi1->CopyTo( path2, true );
      Console::WriteLine( "The second Copy operation succeeded, which is expected." );
   }
   catch ( Exception^ ) 
   {
      Console::WriteLine( "Double copying was not allowed, which is not expected." );
   }
}
//This code produces output similar to the following; 
//results may vary based on the computer/file structure/etc.:
//
//The second Copy operation succeeded, which is expected.
using System;
using System.IO;

class Test
{

    public static void Main()
    {
        string path = @"c:\SoureFile.txt";
        string path2 = @"c:\NewFile.txt";
        FileInfo fi1 = new FileInfo(path);
        FileInfo fi2 = new FileInfo(path2);

        try
        {
            // Create the source file.
            using (FileStream fs = fi1.Create()) { }

            //Ensure that the target file does not exist.
            if (File.Exists(path2))
            {
                fi2.Delete();
            }

            //Copy the file.f
            fi1.CopyTo(path2);
            Console.WriteLine("{0} was copied to {1}.", path, path2);
        }
        catch (IOException ioex)
        {
            Console.WriteLine(ioex.Message);
        }
    }
}
Imports System.IO

Public Class Test

    Public Shared Sub Main()
        'Specify the directories you want to manipulate.
        Dim path As String = "c:\SourceFile.txt"
        Dim path2 As String = "c:\NewFile.txt"
        Dim fi As FileInfo = New FileInfo(path)
        Dim fi2 As FileInfo = New FileInfo(path2)

        Try
            Using fs As FileStream = fi.Create()
            End Using

            'Ensure that the target does not exist.
            If File.Exists(path2) Then
                fi2.Delete()
            End If
            
            'Copy the file.
            fi.CopyTo(path2)
            Console.WriteLine("{0} was copied to {1}.", path, path2)

        Catch ioex As IOException
            Console.WriteLine(ioex.Message)
        End Try
    End Sub
End Class

下列範例示範如何將一個檔案複製到另一個檔案,如果目的地檔案已經存在,則會擲回例外狀況。

using namespace System;
using namespace System::IO;
int main()
{
   try
   {
      
      // Create a reference to a file, which might or might not exist.
      // If it does not exist, it is not yet created.
      FileInfo^ fi = gcnew FileInfo( "temp.txt" );
      
      // Create a writer, ready to add entries to the file.
      StreamWriter^ sw = fi->AppendText();
      sw->WriteLine( "Add as many lines as you like..." );
      sw->WriteLine( "Add another line to the output..." );
      sw->Flush();
      sw->Close();
      
      // Get the information out of the file and display it.
      StreamReader^ sr = gcnew StreamReader( fi->OpenRead() );
      Console::WriteLine( "This is the information in the first file:" );
      while ( sr->Peek() != -1 )
            Console::WriteLine( sr->ReadLine() );
      
      // Copy this file to another file. The file will not be overwritten if it already exists.
      FileInfo^ newfi = fi->CopyTo( "newTemp.txt" );
      
      // Get the information out of the new file and display it.* sr = new StreamReader(newfi->OpenRead());
      Console::WriteLine( "{0}This is the information in the second file:", Environment::NewLine );
      while ( sr->Peek() != -1 )
            Console::WriteLine( sr->ReadLine() );
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( e->Message );
   }

}
//This code produces output similar to the following; 
//results may vary based on the computer/file structure/etc.:
//
//This is the information in the first file:
//Add as many lines as you like...
//Add another line to the output...
//
//This is the information in the second file:
using System;
using System.IO;

public class CopyToTest
{
    public static void Main()
    {
        try
        {
            // Create a reference to a file, which might or might not exist.
            // If it does not exist, it is not yet created.
            FileInfo fi = new FileInfo("temp.txt");
            // Create a writer, ready to add entries to the file.
            StreamWriter sw = fi.AppendText();
            sw.WriteLine("Add as many lines as you like...");
            sw.WriteLine("Add another line to the output...");
            sw.Flush();
            sw.Close();
            // Get the information out of the file and display it.
            StreamReader sr = new StreamReader(fi.OpenRead());
            Console.WriteLine("This is the information in the first file:");
            while (sr.Peek() != -1)
                Console.WriteLine(sr.ReadLine());
            // Copy this file to another file. The file will not be overwritten if it already exists.
            FileInfo newfi = fi.CopyTo("newTemp.txt");
            // Get the information out of the new file and display it.
            sr = new StreamReader(newfi.OpenRead());
            Console.WriteLine("{0}This is the information in the second file:", Environment.NewLine);
            while (sr.Peek() != -1)
                Console.WriteLine(sr.ReadLine());
        }
        catch(Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//This is the information in the first file:
//Add as many lines as you like...
//Add another line to the output...

//This is the information in the second file:
//Add as many lines as you like...
//Add another line to the output...
Imports System.IO

Public Class CopyToTest
    Public Shared Sub Main()
        Try
            ' Create a reference to a file, which might or might not exist.
            ' If it does not exist, it is not yet created.
            Dim fi As New FileInfo("temp.txt")
            ' Create a writer, ready to add entries to the file.
            Dim sw As StreamWriter = fi.AppendText()
            sw.WriteLine("Add as many lines as you like...")
            sw.WriteLine("Add another line to the output...")
            sw.Flush()
            sw.Close()
            ' Get the information out of the file and display it.
            Dim sr As New StreamReader(fi.OpenRead())
            Console.WriteLine("This is the information in the first file:")
            While sr.Peek() <> -1
                Console.WriteLine(sr.ReadLine())
            End While
            ' Copy this file to another file.
            Dim newfi As FileInfo = fi.CopyTo("newTemp.txt")
            ' Get the information out of the new file and display it.
            sr = New StreamReader(newfi.OpenRead())
            Console.WriteLine("{0}This is the information in the second file:", Environment.NewLine)
            While sr.Peek() <> -1
                Console.WriteLine(sr.ReadLine())
            End While
        Catch e As Exception
            Console.WriteLine(e.Message)
        End Try
    End Sub
End Class
'This code produces output similar to the following; 
'results may vary based on the computer/file structure/etc.:
'
'This is the information in the first file:
'Add as many lines as you like...
'Add another line to the output...
'
'This is the information in the second file:
'Add as many lines as you like...
'Add another line to the output...

備註

CopyTo(String, Boolean)使用 方法來允許覆寫現有的檔案。

警告

盡可能避免使用簡短檔案名, (例如 XXXXXX~1.XXX) 此方法。 如果兩個檔案具有對等的簡短檔案名,則此方法可能會失敗並引發例外狀況和/或導致不想要的行為

另請參閱

適用於

CopyTo(String, Boolean)

來源:
FileInfo.cs
來源:
FileInfo.cs
來源:
FileInfo.cs

複製現有的檔案到新檔案,允許覆寫現有的檔案。

public:
 System::IO::FileInfo ^ CopyTo(System::String ^ destFileName, bool overwrite);
public System.IO.FileInfo CopyTo (string destFileName, bool overwrite);
member this.CopyTo : string * bool -> System.IO.FileInfo
Public Function CopyTo (destFileName As String, overwrite As Boolean) As FileInfo

參數

destFileName
String

要複製的目標新檔案名稱。

overwrite
Boolean

若允許覆寫現有檔案,則為 true,否則為 false

傳回

新檔案,或現有檔案的覆寫 (如果 overwritetrue)。 如果檔案存在而且 overwritefalse,則會擲回 IOException

例外狀況

.NET Framework和 2.1 之前的 .NET Core 版本: destFileName 是空的、只包含空白字元,或包含不正確字元。

發生錯誤,或者目的檔案已經存在,而且 overwritefalse

呼叫端沒有必要的權限。

destFileNamenull

destFileName 中指定的目錄不存在。

傳入了目錄路徑,或者檔案正要移至不同的磁碟機。

指定的路徑、檔案名稱,或兩者都超出系統定義的長度上限。

destFileName 在字串的中間包含一個冒號 (:)。

範例

下列範例示範 方法的兩個 CopyTo 多載。

using namespace System;
using namespace System::IO;

int main()
{
   String^ path = "c:\\MyTest.txt";
   String^ path2 = "c:\\MyTest.txttemp";
   FileInfo^ fi1 = gcnew FileInfo( path );
   FileInfo^ fi2 = gcnew FileInfo( path2 );
   try
   {
      // Create the file and clean up handles.
      FileStream^ fs = fi1->Create();
      if ( fs )
         delete (IDisposable^)fs;
      
      //Ensure that the target does not exist.
      fi2->Delete();
      
      //Copy the file.
      fi1->CopyTo( path2 );
      Console::WriteLine( "{0} was copied to {1}.", path, path2 );
      
      //Try to copy it again, which should succeed.
      fi1->CopyTo( path2, true );
      Console::WriteLine( "The second Copy operation succeeded, which is expected." );
   }
   catch ( Exception^ ) 
   {
      Console::WriteLine( "Double copying was not allowed, which is not expected." );
   }
}
//This code produces output similar to the following; 
//results may vary based on the computer/file structure/etc.:
//
//The second Copy operation succeeded, which is expected.
using System;
using System.IO;

class Test
{

    public static void Main()
    {
        string path = @"c:\SoureFile.txt";
        string path2 = @"c:\NewFile.txt";
        FileInfo fi1 = new FileInfo(path);
        FileInfo fi2 = new FileInfo(path2);

        try
        {
            // Create the source file.
            using (FileStream fs = fi1.Create()) { }

            //Ensure that the target file does not exist.
            if (File.Exists(path2))
            {
                fi2.Delete();
            }

            //Copy the file.f
            fi1.CopyTo(path2);
            Console.WriteLine("{0} was copied to {1}.", path, path2);
        }
        catch (IOException ioex)
        {
            Console.WriteLine(ioex.Message);
        }
    }
}
Imports System.IO

Public Class Test

    Public Shared Sub Main()
        'Specify the directories you want to manipulate.
        Dim path As String = "c:\SourceFile.txt"
        Dim path2 As String = "c:\NewFile.txt"
        Dim fi As FileInfo = New FileInfo(path)
        Dim fi2 As FileInfo = New FileInfo(path2)

        Try
            Using fs As FileStream = fi.Create()
            End Using

            'Ensure that the target does not exist.
            If File.Exists(path2) Then
                fi2.Delete()
            End If
            
            'Copy the file.
            fi.CopyTo(path2)
            Console.WriteLine("{0} was copied to {1}.", path, path2)

        Catch ioex As IOException
            Console.WriteLine(ioex.Message)
        End Try
    End Sub
End Class

下列範例示範如何將一個檔案複製到另一個檔案,指定是否覆寫已經存在的檔案。

using namespace System;
using namespace System::IO;
int main()
{
   
   // Create a reference to a file, which might or might not exist.
   // If it does not exist, it is not yet created.
   FileInfo^ fi = gcnew FileInfo( "temp.txt" );
   
   // Create a writer, ready to add entries to the file.
   StreamWriter^ sw = fi->AppendText();
   sw->WriteLine( "Add as many lines as you like..." );
   sw->WriteLine( "Add another line to the output..." );
   sw->Flush();
   sw->Close();
   
   // Get the information out of the file and display it.
   StreamReader^ sr = gcnew StreamReader( fi->OpenRead() );
   Console::WriteLine( "This is the information in the first file:" );
   while ( sr->Peek() != -1 )
      Console::WriteLine( sr->ReadLine() );

   
   // Copy this file to another file. The true parameter specifies
   // that the file will be overwritten if it already exists.
   FileInfo^ newfi = fi->CopyTo( "newTemp.txt", true );
   
   // Get the information out of the new file and display it.* sr = new StreamReader( newfi->OpenRead() );
   Console::WriteLine( "{0}This is the information in the second file:", Environment::NewLine );
   while ( sr->Peek() != -1 )
      Console::WriteLine( sr->ReadLine() );
}
//This code produces output similar to the following; 
//results may vary based on the computer/file structure/etc.:
//
//This is the information in the first file:
//Add as many lines as you like...
//Add another line to the output...
//This is the information in the second file:
//
using System;
using System.IO;

public class CopyToTest
{
    public static void Main()
    {
        // Create a reference to a file, which might or might not exist.
        // If it does not exist, it is not yet created.
        FileInfo fi = new FileInfo("temp.txt");
        // Create a writer, ready to add entries to the file.
        StreamWriter sw = fi.AppendText();
        sw.WriteLine("Add as many lines as you like...");
        sw.WriteLine("Add another line to the output...");
        sw.Flush();
        sw.Close();
        // Get the information out of the file and display it.
        StreamReader sr = new StreamReader( fi.OpenRead() );
        Console.WriteLine("This is the information in the first file:");
        while (sr.Peek() != -1)
            Console.WriteLine( sr.ReadLine() );
        // Copy this file to another file. The true parameter specifies
        // that the file will be overwritten if it already exists.
        FileInfo newfi = fi.CopyTo("newTemp.txt", true);
        // Get the information out of the new file and display it.
        sr = new StreamReader( newfi.OpenRead() );
        Console.WriteLine("{0}This is the information in the second file:", Environment.NewLine);
        while (sr.Peek() != -1)
            Console.WriteLine( sr.ReadLine() );
    }
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//This is the information in the first file:
//Add as many lines as you like...
//Add another line to the output...
//Add as many lines as you like...
//Add another line to the output...

//This is the information in the second file:
//Add as many lines as you like...
//Add another line to the output...
//Add as many lines as you like...
//Add another line to the output...
Imports System.IO

Public Class CopyToTest
    Public Shared Sub Main()
        ' Create a reference to a file, which might or might not exist.
        ' If it does not exist, it is not yet created.
        Dim fi As New FileInfo("temp.txt")
        ' Create a writer, ready to add entries to the file.
        Dim sw As StreamWriter = fi.AppendText()
        sw.WriteLine("Add as many lines as you like...")
        sw.WriteLine("Add another line to the output...")
        sw.Flush()
        sw.Close()
        ' Get the information out of the file and display it.
        Dim sr As New StreamReader(fi.OpenRead())
        Console.WriteLine("This is the information in the first file:")
        While sr.Peek() <> -1
            Console.WriteLine(sr.ReadLine())
        End While
        ' Copy this file to another file. The true parameter specifies 
        ' that the file will be overwritten if it already exists.
        Dim newfi As FileInfo = fi.CopyTo("newTemp.txt", True)
        ' Get the information out of the new file and display it.
        sr = New StreamReader(newfi.OpenRead())
        Console.WriteLine("{0}This is the information in the second file:", Environment.NewLine)
        While sr.Peek() <> -1
            Console.WriteLine(sr.ReadLine())
        End While
    End Sub
End Class
'This code produces output similar to the following; 
'results may vary based on the computer/file structure/etc.:
'
'This is the information in the first file:
'Add as many lines as you like...
'Add another line to the output...
'
'This is the information in the second file:
'Add as many lines as you like...
'Add another line to the output...
'

備註

使用這個方法來允許或防止覆寫現有的檔案。 CopyTo(String)使用 方法來防止預設覆寫現有的檔案。

警告

盡可能避免使用簡短檔案名, (例如 XXXXXX~1.XXX) 此方法。 如果兩個檔案具有對等的簡短檔案名,則此方法可能會失敗並引發例外狀況和/或導致不想要的行為

另請參閱

適用於