File.Copy 메서드

정의

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

오버로드

Copy(String, String, Boolean)

새 파일에 기존 파일을 복사합니다. 같은 이름의 파일을 덮어쓸 수 있습니다.

Copy(String, String)

새 파일에 기존 파일을 복사합니다. 같은 이름의 파일을 덮어쓸 수는 없습니다.

Copy(String, String, Boolean)

Source:
File.cs
Source:
File.cs
Source:
File.cs

새 파일에 기존 파일을 복사합니다. 같은 이름의 파일을 덮어쓸 수 있습니다.

public:
 static void Copy(System::String ^ sourceFileName, System::String ^ destFileName, bool overwrite);
public static void Copy (string sourceFileName, string destFileName, bool overwrite);
static member Copy : string * string * bool -> unit
Public Shared Sub Copy (sourceFileName As String, destFileName As String, overwrite As Boolean)

매개 변수

sourceFileName
String

복사할 파일입니다.

destFileName
String

대상 파일의 이름입니다. 대상 파일 이름은 디렉터리가 될 수 없습니다.

overwrite
Boolean

true 대상 파일이 이미 있는 경우 대체해야 하면 이고, 그렇지 않으면 입니다 false.

예외

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

또는

destFileName이(가) 읽기 전용입니다.

또는

overwritetrue이고, destFileName은 있지만 숨겨져 있고, sourceFileName은 숨겨지지 않습니다.

sourceFileName 또는 destFileName이 빈 문자열이거나, 공백만을 포함하거나, 하나 이상의 잘못된 문자를 포함합니다. GetInvalidPathChars() 메서드를 사용하여 잘못된 문자를 쿼리할 수 있습니다.

또는

sourceFileName 또는 destFileName이 디렉터리를 지정합니다.

sourceFileName 또는 destFileNamenull인 경우

지정된 경로, 파일 이름 또는 둘 다가 시스템에서 정의한 최대 길이를 초과합니다.

sourceFileName 또는 destFileName에 지정된 경로가 잘못되었습니다(예: 매핑되지 않은 드라이브에 있음).

sourceFileName을 찾을 수 없습니다.

destFileName이(가) 있으며 overwrite이(가) false입니다.

또는

I/O 오류가 발생했습니다.

sourceFileName 또는 destFileName의 형식이 잘못되었습니다.

예제

다음 예제에서는 C:\archives\2008 백업 폴더에 파일을 복사합니다. 다음과 같이 메서드의 두 오버로드를 Copy 사용합니다.

  • 먼저 메서드 오버로드를 File.Copy(String, String) 사용하여 텍스트(.txt) 파일을 복사합니다. 이 코드는 이 오버로드가 이미 복사된 파일을 덮어쓸 수 없음을 보여 줍니다.

그런 다음 메서드 오버로드를 File.Copy(String, String, Boolean) 사용하여 그림(.jpg 파일)을 복사합니다. 이 코드는 이 오버로드가 이미 복사된 파일을 덮어쓸 수 있음을 보여 줍니다.

string sourceDir = @"c:\current";
string backupDir = @"c:\archives\2008";

try
{
    string[] picList = Directory.GetFiles(sourceDir, "*.jpg");
    string[] txtList = Directory.GetFiles(sourceDir, "*.txt");

    // Copy picture files.
    foreach (string f in picList)
    {
        // Remove path from the file name.
        string fName = f.Substring(sourceDir.Length + 1);

        // Use the Path.Combine method to safely append the file name to the path.
        // Will overwrite if the destination file already exists.
        File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), true);
    }

    // Copy text files.
    foreach (string f in txtList)
    {

        // Remove path from the file name.
        string fName = f.Substring(sourceDir.Length + 1);

        try
        {
            // Will not overwrite if the destination file already exists.
            File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName));
        }

        // Catch exception if the file was already copied.
        catch (IOException copyError)
        {
            Console.WriteLine(copyError.Message);
        }
    }

    // Delete source files that were copied.
    foreach (string f in txtList)
    {
        File.Delete(f);
    }
    foreach (string f in picList)
    {
        File.Delete(f);
    }
}

catch (DirectoryNotFoundException dirNotFound)
{
    Console.WriteLine(dirNotFound.Message);
}
let sourceDir = @"c:\current"
let backupDir = @"c:\archives\2008"

try
    let picList = Directory.GetFiles(sourceDir, "*.jpg")
    let txtList = Directory.GetFiles(sourceDir, "*.txt")

    // Copy picture files.
    for f in picList do
        // Remove path from the file name.
        let fName = f.Substring(sourceDir.Length + 1)

        // Use the Path.Combine method to safely append the file name to the path.
        // Will overwrite if the destination file already exists.
        File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), true)

    // Copy text files.
    for f in txtList do
        // Remove path from the file name.
        let fName = f.Substring(sourceDir.Length + 1)

        try
            // Will not overwrite if the destination file already exists.
            File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName))

        // Catch exception if the file was already copied.
        with
        | :? IOException as copyError -> printfn $"{copyError.Message}"

    // Delete source files that were copied.
    for f in txtList do
        File.Delete f

    for f in picList do
        File.Delete f

// Catch exception if the file was already copied.
with
| :? DirectoryNotFoundException as dirNotFound -> printfn $"{dirNotFound.Message}"
Dim sourceDir As String = "c:\current"
Dim backupDir As String = "c:\archives\2008"

Try
    Dim picList As String() = Directory.GetFiles(sourceDir, "*.jpg")
    Dim txtList As String() = Directory.GetFiles(sourceDir, "*.txt")

    ' Copy picture files.
    For Each f As String In picList
        'Remove path from the file name.
        Dim fName As String = f.Substring(sourceDir.Length + 1)

        ' Use the Path.Combine method to safely append the file name to the path.
        ' Will overwrite if the destination file already exists.
        File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), True)
    Next

    ' Copy text files.
    For Each f As String In txtList

        'Remove path from the file name.
        Dim fName As String = f.Substring(sourceDir.Length + 1)

        Try
            ' Will not overwrite if the destination file already exists.
            File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName))

            ' Catch exception if the file was already copied.
        Catch copyError As IOException
            Console.WriteLine(copyError.Message)
        End Try
    Next

    For Each f As String In txtList
        File.Delete(f)
    Next

    For Each f As String In picList
        File.Delete(f)
    Next

Catch dirNotFound As DirectoryNotFoundException
    Console.WriteLine(dirNotFound.Message)
End Try

설명

destFileName 매개 변수는 sourceFileName 상대 또는 절대 경로 정보를 지정할 수 있습니다. 상대 경로 정보는 현재 작업 디렉터리를 기준으로 해석됩니다. 이 메서드는 매개 변수의 와일드카드 문자를 지원하지 않습니다.

원본 파일의 특성은 복사된 파일에 유지됩니다.

일반적인 I/O 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

Copy(String, String)

Source:
File.cs
Source:
File.cs
Source:
File.cs

새 파일에 기존 파일을 복사합니다. 같은 이름의 파일을 덮어쓸 수는 없습니다.

public:
 static void Copy(System::String ^ sourceFileName, System::String ^ destFileName);
public static void Copy (string sourceFileName, string destFileName);
static member Copy : string * string -> unit
Public Shared Sub Copy (sourceFileName As String, destFileName As String)

매개 변수

sourceFileName
String

복사할 파일입니다.

destFileName
String

대상 파일의 이름입니다. 대상 파일 이름은 디렉터리나 기존 파일일 수 없습니다.

예외

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

sourceFileName 또는 destFileName이 빈 문자열이거나, 공백만을 포함하거나, 하나 이상의 잘못된 문자를 포함합니다. GetInvalidPathChars() 메서드를 사용하여 잘못된 문자를 쿼리할 수 있습니다.

또는

sourceFileName 또는 destFileName이 디렉터리를 지정합니다.

sourceFileName 또는 destFileNamenull인 경우

지정된 경로, 파일 이름 또는 둘 다가 시스템에서 정의한 최대 길이를 초과합니다.

sourceFileName 또는 destFileName에 지정된 경로가 잘못되었습니다(예: 매핑되지 않은 드라이브에 있음).

sourceFileName을 찾을 수 없습니다.

destFileName이 있습니다.

또는

I/O 오류가 발생했습니다.

sourceFileName 또는 destFileName의 형식이 잘못되었습니다.

예제

다음 예제에서는 C:\archives\2008 백업 폴더에 파일을 복사합니다. 다음과 같이 메서드의 두 오버로드를 Copy 사용합니다.

  • 먼저 메서드 오버로드를 File.Copy(String, String) 사용하여 텍스트(.txt) 파일을 복사합니다. 이 코드는 이 오버로드가 이미 복사된 파일을 덮어쓸 수 없음을 보여 줍니다.

  • 그런 다음 메서드 오버로드를 File.Copy(String, String, Boolean) 사용하여 그림(.jpg 파일)을 복사합니다. 이 코드는 이 오버로드가 이미 복사된 파일을 덮어쓸 수 있음을 보여 줍니다.

string sourceDir = @"c:\current";
string backupDir = @"c:\archives\2008";

try
{
    string[] picList = Directory.GetFiles(sourceDir, "*.jpg");
    string[] txtList = Directory.GetFiles(sourceDir, "*.txt");

    // Copy picture files.
    foreach (string f in picList)
    {
        // Remove path from the file name.
        string fName = f.Substring(sourceDir.Length + 1);

        // Use the Path.Combine method to safely append the file name to the path.
        // Will overwrite if the destination file already exists.
        File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), true);
    }

    // Copy text files.
    foreach (string f in txtList)
    {

        // Remove path from the file name.
        string fName = f.Substring(sourceDir.Length + 1);

        try
        {
            // Will not overwrite if the destination file already exists.
            File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName));
        }

        // Catch exception if the file was already copied.
        catch (IOException copyError)
        {
            Console.WriteLine(copyError.Message);
        }
    }

    // Delete source files that were copied.
    foreach (string f in txtList)
    {
        File.Delete(f);
    }
    foreach (string f in picList)
    {
        File.Delete(f);
    }
}

catch (DirectoryNotFoundException dirNotFound)
{
    Console.WriteLine(dirNotFound.Message);
}
let sourceDir = @"c:\current"
let backupDir = @"c:\archives\2008"

try
    let picList = Directory.GetFiles(sourceDir, "*.jpg")
    let txtList = Directory.GetFiles(sourceDir, "*.txt")

    // Copy picture files.
    for f in picList do
        // Remove path from the file name.
        let fName = f.Substring(sourceDir.Length + 1)

        // Use the Path.Combine method to safely append the file name to the path.
        // Will overwrite if the destination file already exists.
        File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), true)

    // Copy text files.
    for f in txtList do
        // Remove path from the file name.
        let fName = f.Substring(sourceDir.Length + 1)

        try
            // Will not overwrite if the destination file already exists.
            File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName))

        // Catch exception if the file was already copied.
        with
        | :? IOException as copyError -> printfn $"{copyError.Message}"

    // Delete source files that were copied.
    for f in txtList do
        File.Delete f

    for f in picList do
        File.Delete f

// Catch exception if the file was already copied.
with
| :? DirectoryNotFoundException as dirNotFound -> printfn $"{dirNotFound.Message}"
Dim sourceDir As String = "c:\current"
Dim backupDir As String = "c:\archives\2008"

Try
    Dim picList As String() = Directory.GetFiles(sourceDir, "*.jpg")
    Dim txtList As String() = Directory.GetFiles(sourceDir, "*.txt")

    ' Copy picture files.
    For Each f As String In picList
        'Remove path from the file name.
        Dim fName As String = f.Substring(sourceDir.Length + 1)

        ' Use the Path.Combine method to safely append the file name to the path.
        ' Will overwrite if the destination file already exists.
        File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), True)
    Next

    ' Copy text files.
    For Each f As String In txtList

        'Remove path from the file name.
        Dim fName As String = f.Substring(sourceDir.Length + 1)

        Try
            ' Will not overwrite if the destination file already exists.
            File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName))

            ' Catch exception if the file was already copied.
        Catch copyError As IOException
            Console.WriteLine(copyError.Message)
        End Try
    Next

    For Each f As String In txtList
        File.Delete(f)
    Next

    For Each f As String In picList
        File.Delete(f)
    Next

Catch dirNotFound As DirectoryNotFoundException
    Console.WriteLine(dirNotFound.Message)
End Try

설명

이 메서드는 매개 변수가 로 Copy(String, String, Boolean) 설정된 false메서드 오버로드와 overwrite 동일합니다.

destFileName 매개 변수는 sourceFileName 상대 또는 절대 경로 정보를 지정할 수 있습니다. 상대 경로 정보는 현재 작업 디렉터리를 기준으로 해석됩니다. 현재 작업 디렉터리를 가져오려면 메서드를 Directory.GetCurrentDirectory 참조하세요. 이 메서드는 매개 변수의 와일드카드 문자를 지원하지 않습니다.

원본 파일의 특성은 복사된 파일에 유지됩니다.

추가 정보

적용 대상