FileInfo.CopyTo メソッド

定義

既存のファイルを新しいファイルにコピーします。Copies an existing file to a new file.

オーバーロード

CopyTo(String)

既存のファイルを上書きできないようにして、既存のファイルを新しいファイルにコピーします。Copies an existing file to a new file, disallowing the overwriting of an existing file.

CopyTo(String, Boolean)

既存のファイルを上書きできるようにして、既存のファイルを新しいファイルにコピーします。Copies an existing file to a new file, allowing the overwriting of an existing file.

CopyTo(String)

既存のファイルを上書きできないようにして、既存のファイルを新しいファイルにコピーします。Copies an existing file to a new file, disallowing the overwriting of an existing file.

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

コピー先の新しいファイルの名前。The name of the new file to copy to.

戻り値

完全修飾パスを含む新しいファイル。A new file with a fully qualified path.

例外

destFileName は空で、空白のみで構成されているか、正しくない文字を含んでいます。destFileName is empty, contains only white spaces, or contains invalid characters.

エラーが発生したか、リンク先ファイルが既に存在します。An error occurs, or the destination file already exists.

呼び出し元に、必要なアクセス許可がありません。The caller does not have the required permission.

destFileNamenull です。destFileName is null.

ディレクトリ パスが渡されるか、ファイルが別のドライブに移動されています。A directory path is passed in, or the file is being moved to a different drive.

destFileName で指定されたディレクトリが存在しません。The directory specified in destFileName does not exist.

指定したパス、ファイル名、またはその両方がシステム定義の最大長を超えています。The specified path, file name, or both exceed the system-defined maximum length.

destFileName の文字列内にコロン (:) が含まれていますが、ボリュームを指定していません。destFileName contains a colon (:) within the string but does not specify the volume.

次の例は、 CopyToメソッドの両方のオーバーロードを示しています。The following example demonstrates both overloads of the CopyTo method.

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

次の例では、あるファイルを別のファイルにコピーする方法を示します。コピー先のファイルが既に存在する場合は、例外がスローされます。The following example demonstrates copying one file to another file, throwing an exception if the destination file already exists.

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)使用して、既存のファイルを上書きできるようにします。Use the CopyTo(String, Boolean) method to allow overwriting of an existing file.

注意事項

可能な限り、この方法で短いファイル名 (XXXXXX ~ 1. XXX など) を使用しないようにしてください。Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. 2つのファイルの短いファイル名が同じ場合、このメソッドは失敗し、例外が発生するか、または望ましくない動作が発生する可能性があります。If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior

セキュリティ

FileIOPermission
ファイルの読み取りと書き込みを行います。for reading and writing files. 関連付けられReadた列挙型:、WriteAssociated enumerations: Read, Write

こちらもご覧ください

CopyTo(String, Boolean)

既存のファイルを上書きできるようにして、既存のファイルを新しいファイルにコピーします。Copies an existing file to a new file, allowing the overwriting of an existing file.

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

コピー先の新しいファイルの名前。The name of the new file to copy to.

overwrite
Boolean

既存のファイルを上書きできるようにする場合は true。それ以外の場合は falsetrue to allow an existing file to be overwritten; otherwise, false.

戻り値

新しいファイル。または、overwritetrue の場合は、既存のファイルを上書きしたファイル。A new file, or an overwrite of an existing file if overwrite is true. ファイルが存在しており、overwritefalse の場合は、IOException がスローされます。If the file exists and overwrite is false, an IOException is thrown.

例外

destFileName は空で、空白のみで構成されているか、正しくない文字を含んでいます。destFileName is empty, contains only white spaces, or contains invalid characters.

エラーが発生したか、リンク先ファイルが既に存在し、overwritefalse です。An error occurs, or the destination file already exists and overwrite is false.

呼び出し元に、必要なアクセス許可がありません。The caller does not have the required permission.

destFileNamenull です。destFileName is null.

destFileName で指定されたディレクトリが存在しません。The directory specified in destFileName does not exist.

ディレクトリ パスが渡されるか、ファイルが別のドライブに移動されています。A directory path is passed in, or the file is being moved to a different drive.

指定したパス、ファイル名、またはその両方がシステム定義の最大長を超えています。The specified path, file name, or both exceed the system-defined maximum length.

destFileName の文字列の途中にコロン (:) が含まれています。destFileName contains a colon (:) in the middle of the string.

次の例は、 CopyToメソッドの両方のオーバーロードを示しています。The following example demonstrates both overloads of the CopyTo method.

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

次の例では、既存のファイルを上書きするかどうかを指定して、1つのファイルを別のファイルにコピーする方法を示します。The following example demonstrates copying one file to another file, specifying whether to overwrite a file that already exists.

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...
'

注釈

このメソッドを使用して、既存のファイルの上書きを許可または禁止します。Use this method to allow or prevent overwriting of an existing file. 既定でCopyTo(String)既存のファイルが上書きされないようにするには、メソッドを使用します。Use the CopyTo(String) method to prevent overwriting of an existing file by default.

注意事項

可能な限り、この方法で短いファイル名 (XXXXXX ~ 1. XXX など) を使用しないようにしてください。Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. 2つのファイルの短いファイル名が同じ場合、このメソッドは失敗し、例外が発生するか、または望ましくない動作が発生する可能性があります。If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior

セキュリティ

FileIOPermission
ファイルの読み取りと書き込みを行います。for reading and writing files. 関連付けられReadた列挙型:、WriteAssociated enumerations: Read, Write

こちらもご覧ください

適用対象