다음을 통해 공유


FileInfo.CopyTo 메서드

정의

새 파일에 기존 파일을 복사합니다.

오버로드

CopyTo(String)

새 파일에 기존 파일을 복사하고 기존 파일을 덮어쓸 수 없도록 합니다.

CopyTo(String, Boolean)

새 파일에 기존 파일을 복사하고 기존 파일을 덮어쓸 수 있도록 합니다.

CopyTo(String)

Source:
FileInfo.cs
Source:
FileInfo.cs
Source:
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

복사할 새 파일의 이름입니다.

반환

정규화된 경로가 있는 새 파일입니다.

예외

2.1 이전의 .NET Framework 및 .NET Core 버전: destFileName 비어 있거나 공백만 포함하거나 잘못된 문자를 포함합니다.

오류가 발생했거나 대상 파일이 이미 있습니다.

호출자에게 필요한 권한이 없는 경우

destFileName이(가) null인 경우

디렉터리 경로를 거치거나 파일이 다른 드라이브로 이동됩니다.

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

다음 예제에서는 한 파일을 다른 파일에 복사하여 대상 파일이 이미 있는 경우 예외를 throw하는 방법을 보여 줍니다.

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)

Source:
FileInfo.cs
Source:
FileInfo.cs
Source:
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이 throw됩니다.

예외

2.1 이전의 .NET Framework 및 .NET Core 버전: destFileName 비어 있거나 공백만 포함하거나 잘못된 문자를 포함합니다.

오류가 발생했거나 대상 파일이 이미 있으며 overwritefalse입니다.

호출자에게 필요한 권한이 없는 경우

destFileName이(가) null인 경우

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)을 사용하지 마세요. 두 파일에 해당하는 짧은 파일 이름이 있는 경우 이 메서드가 실패하여 예외 및/또는 이로 인해 바람직하지 않은 동작이 발생할 수 있습니다.

추가 정보

적용 대상