File.Copy Метод

Определение

Копирует существующий файл в новый файл.

Перегрузки

Copy(String, String, Boolean)

Копирует существующий файл в новый файл. Перезапись файла с тем же именем разрешена.

Copy(String, String)

Копирует существующий файл в новый файл. Перезапись файла с тем же именем не разрешена.

Copy(String, String, Boolean)

Исходный код:
File.cs
Исходный код:
File.cs
Исходный код:
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 доступен только для чтения.

-или-

overwrite равен true, destFileName существует и скрыт, но sourceFileName не скрыт.

sourceFileName или destFileName представляет собой строку нулевой длины, строку, содержащую только пробелы, или строку, содержащую один или несколько недопустимых символов. Вы можете запросить недопустимые символы с помощью метода GetInvalidPathChars().

-или-

Параметр sourceFileName или destFileName определяет каталог.

Параметр sourceFileName или destFileName имеет значение null.

Указанный путь, имя файла или оба значения превышают максимальную длину, заданную в системе.

В sourceFileName или destFileName указан недопустимый путь (например, ведущий на несопоставленный диск).

Не удалось найти sourceFileName.

destFileName существует, и overwrite равно false.

-или-

Произошла ошибка ввода-вывода.

Параметр 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

Комментарии

Параметры sourceFileName и destFileName могут указывать относительные или абсолютные сведения о пути. Относительные сведения о пути интерпретируются как относительные относительно текущего рабочего каталога. Этот метод не поддерживает подстановочные знаки в параметрах.

Атрибуты исходного файла сохраняются в скопированном файле.

Список распространенных задач ввода-вывода см. в разделе Общие задачи ввода-вывода.

См. также раздел

Применяется к

Copy(String, String)

Исходный код:
File.cs
Исходный код:
File.cs
Исходный код:
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 или destFileName имеет значение null.

Указанный путь, имя файла или оба значения превышают максимальную длину, заданную в системе.

В sourceFileName или destFileName указан недопустимый путь (например, ведущий на несопоставленный диск).

Не удалось найти sourceFileName.

destFileName существует.

-или-

Произошла ошибка ввода-вывода.

Параметр 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) метода с параметром overwrite , равным false.

Параметры sourceFileName и destFileName могут указывать относительные или абсолютные сведения о пути. Относительные сведения о пути интерпретируются как относительные относительно текущего рабочего каталога. Чтобы получить текущий рабочий каталог, см. Directory.GetCurrentDirectory метод . Этот метод не поддерживает подстановочные знаки в параметрах.

Атрибуты исходного файла сохраняются в скопированном файле.

См. также раздел

Применяется к