FileInfo.Replace Método

Definição

Substitui o conteúdo de um arquivo especificado pelo arquivo descrito pelo objeto atual FileInfo , excluindo o arquivo original e criando um backup do arquivo substituído.

Sobrecargas

Nome Description
Replace(String, String)

Substitui o conteúdo de um arquivo especificado pelo arquivo descrito pelo objeto atual FileInfo , excluindo o arquivo original e criando um backup do arquivo substituído.

Replace(String, String, Boolean)

Substitui o conteúdo de um arquivo especificado pelo arquivo descrito pelo objeto atual FileInfo , excluindo o arquivo original e criando um backup do arquivo substituído. Também especifica se os erros de mesclagem devem ser ignorados.

Comentários

Use os Replace métodos quando precisar substituir rapidamente um arquivo pelo conteúdo do arquivo descrito pelo objeto atual FileInfo .

Replace(String, String)

Substitui o conteúdo de um arquivo especificado pelo arquivo descrito pelo objeto atual FileInfo , excluindo o arquivo original e criando um backup do arquivo substituído.

public:
 System::IO::FileInfo ^ Replace(System::String ^ destinationFileName, System::String ^ destinationBackupFileName);
[System.Runtime.InteropServices.ComVisible(false)]
public System.IO.FileInfo Replace(string destinationFileName, string destinationBackupFileName);
public System.IO.FileInfo Replace(string destinationFileName, string destinationBackupFileName);
[<System.Runtime.InteropServices.ComVisible(false)>]
member this.Replace : string * string -> System.IO.FileInfo
member this.Replace : string * string -> System.IO.FileInfo
Public Function Replace (destinationFileName As String, destinationBackupFileName As String) As FileInfo

Parâmetros

destinationFileName
String

O nome de um arquivo a ser substituído pelo arquivo atual.

destinationBackupFileName
String

O nome de um arquivo com o qual criar um backup do arquivo descrito pelo destinationFileName parâmetro.

Retornos

Um FileInfo objeto que encapsula informações sobre o arquivo descrito pelo destinationFileName parâmetro.

Atributos

Exceções

O caminho descrito pelo destinationFileName parâmetro não era de uma forma legal.

-ou-

O caminho descrito pelo destinationBackupFileName parâmetro não era de uma forma legal.

O destinationFileName parâmetro é null.

Não foi possível encontrar o arquivo descrito pelo objeto atual FileInfo .

-ou-

Não foi possível encontrar o destinationFileName arquivo descrito pelo parâmetro.

O sistema operacional atual não é o Microsoft Windows NT ou posterior.

Exemplos

O exemplo a seguir usa o Replace método para substituir um arquivo por outro arquivo e criar um backup do arquivo substituído.

using System;
using System.IO;

namespace FileSystemExample
{
    class FileExample
    {
        public static void Main()
        {
            try
            {
                // originalFile and fileToReplace must contain the path to files that already exist in the
                // file system. backUpOfFileToReplace is created during the execution of the Replace method.

                string originalFile  = "test.txt";
                string fileToReplace = "test2.txt";
                string backUpOfFileToReplace = "test2.txt.bak";

                if (File.Exists(originalFile) && (File.Exists(fileToReplace)))
                {
                    Console.WriteLine("Move the contents of " + originalFile + " into " + fileToReplace + ", delete "
                        + originalFile + ", and create a backup of " + fileToReplace + ".");

                    // Replace the file.
                    ReplaceFile(originalFile, fileToReplace, backUpOfFileToReplace);

                    Console.WriteLine("Done");
                }
                else
                {
                    Console.WriteLine("Either the file {0} or {1} doesn't " + "exist.", originalFile, fileToReplace);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.ReadLine();
        }

        // Move a file into another file, delete the original, and create a backup of the replaced file.
        public static void ReplaceFile(string fileToMoveAndDelete, string fileToReplace, string backupOfFileToReplace)
        {
            // Create a new FileInfo object.
            FileInfo fInfo = new FileInfo(fileToMoveAndDelete);

            // replace the file.
            fInfo.Replace(fileToReplace, backupOfFileToReplace, false);
        }
    }
}
//Move the contents of test.txt into test2.txt, delete test.txt, and
//create a backup of test2.txt.
//Done
Imports System.IO

Module FileExample

    Sub Main()
        Try
            ' originalFile and fileToReplace must contain the path to files that already exist in the  
            ' file system. backUpOfFileToReplace is created during the execution of the Replace method.

            Dim originalFile As String = "test.xml"
            Dim fileToReplace As String = "test2.xml"
            Dim backUpOfFileToReplace As String = "test2.xml.bak"

            If (File.Exists(originalFile) And (File.Exists(fileToReplace))) Then
                Console.WriteLine("Move the contents of " + originalFile + " into " + fileToReplace + ", delete " + originalFile + ", and create a backup of " + fileToReplace + ".")

                ' Replace the file.
                ReplaceFile(originalFile, fileToReplace, backUpOfFileToReplace)

                Console.WriteLine("Done")

            Else
                Console.WriteLine("Either the file {0} or {1} doesn't " + "exist.", originalFile, fileToReplace)
            End If
        Catch e As Exception
            Console.WriteLine(e.Message)
        End Try

        Console.ReadLine()

    End Sub

    ' Move a file into another file, delete the original, and create a backup of the replaced file.
    Sub ReplaceFile(ByVal fileToMoveAndDelete As String, ByVal fileToReplace As String, ByVal backupOfFileToReplace As String)
        ' Create a new FileInfo object.
        Dim fInfo As New FileInfo(fileToMoveAndDelete)

        ' Replace the file.
        fInfo.Replace(fileToReplace, backupOfFileToReplace, False)

    End Sub
End Module

' Move the contents of test.txt into test2.txt, delete test.txt, and 
' create a backup of test2.txt.
' Done

Comentários

O Replace método substitui o conteúdo de um arquivo especificado pelo conteúdo do arquivo descrito pelo objeto atual FileInfo . Ele também cria um backup do arquivo que foi substituído. Por fim, ele retorna um novo FileInfo objeto que descreve o arquivo substituído.

Passe null para o destinationBackupFileName parâmetro se você não quiser criar um backup do arquivo que está sendo substituído.

Aplica-se a

Replace(String, String, Boolean)

Substitui o conteúdo de um arquivo especificado pelo arquivo descrito pelo objeto atual FileInfo , excluindo o arquivo original e criando um backup do arquivo substituído. Também especifica se os erros de mesclagem devem ser ignorados.

public:
 System::IO::FileInfo ^ Replace(System::String ^ destinationFileName, System::String ^ destinationBackupFileName, bool ignoreMetadataErrors);
[System.Runtime.InteropServices.ComVisible(false)]
public System.IO.FileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors);
public System.IO.FileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors);
[<System.Runtime.InteropServices.ComVisible(false)>]
member this.Replace : string * string * bool -> System.IO.FileInfo
member this.Replace : string * string * bool -> System.IO.FileInfo
Public Function Replace (destinationFileName As String, destinationBackupFileName As String, ignoreMetadataErrors As Boolean) As FileInfo

Parâmetros

destinationFileName
String

O nome de um arquivo a ser substituído pelo arquivo atual.

destinationBackupFileName
String

O nome de um arquivo com o qual criar um backup do arquivo descrito pelo destinationFileName parâmetro.

ignoreMetadataErrors
Boolean

true para ignorar erros de mesclagem (como atributos e ACLs) do arquivo substituído para o arquivo de substituição; caso contrário false.

Retornos

Um FileInfo objeto que encapsula informações sobre o arquivo descrito pelo destinationFileName parâmetro.

Atributos

Exceções

O caminho descrito pelo destinationFileName parâmetro não era de uma forma legal.

-ou-

O caminho descrito pelo destinationBackupFileName parâmetro não era de uma forma legal.

O destinationFileName parâmetro é null.

Não foi possível encontrar o arquivo descrito pelo objeto atual FileInfo .

-ou-

Não foi possível encontrar o destinationFileName arquivo descrito pelo parâmetro.

O sistema operacional atual não é o Microsoft Windows NT ou posterior.

Exemplos

O exemplo a seguir usa o Replace método para substituir um arquivo por outro arquivo e criar um backup do arquivo substituído.

using System;
using System.IO;

namespace FileSystemExample
{
    class FileExample
    {
        public static void Main()
        {
            try
            {
                // originalFile and fileToReplace must contain the path to files that already exist in the
                // file system. backUpOfFileToReplace is created during the execution of the Replace method.

                string originalFile  = "test.txt";
                string fileToReplace = "test2.txt";
                string backUpOfFileToReplace = "test2.txt.bak";

                if (File.Exists(originalFile) && (File.Exists(fileToReplace)))
                {
                    Console.WriteLine("Move the contents of " + originalFile + " into " + fileToReplace + ", delete "
                        + originalFile + ", and create a backup of " + fileToReplace + ".");

                    // Replace the file.
                    ReplaceFile(originalFile, fileToReplace, backUpOfFileToReplace);

                    Console.WriteLine("Done");
                }
                else
                {
                    Console.WriteLine("Either the file {0} or {1} doesn't " + "exist.", originalFile, fileToReplace);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.ReadLine();
        }

        // Move a file into another file, delete the original, and create a backup of the replaced file.
        public static void ReplaceFile(string fileToMoveAndDelete, string fileToReplace, string backupOfFileToReplace)
        {
            // Create a new FileInfo object.
            FileInfo fInfo = new FileInfo(fileToMoveAndDelete);

            // replace the file.
            fInfo.Replace(fileToReplace, backupOfFileToReplace, false);
        }
    }
}
//Move the contents of test.txt into test2.txt, delete test.txt, and
//create a backup of test2.txt.
//Done
Imports System.IO

Module FileExample

    Sub Main()
        Try
            ' originalFile and fileToReplace must contain the path to files that already exist in the  
            ' file system. backUpOfFileToReplace is created during the execution of the Replace method.

            Dim originalFile As String = "test.xml"
            Dim fileToReplace As String = "test2.xml"
            Dim backUpOfFileToReplace As String = "test2.xml.bak"

            If (File.Exists(originalFile) And (File.Exists(fileToReplace))) Then
                Console.WriteLine("Move the contents of " + originalFile + " into " + fileToReplace + ", delete " + originalFile + ", and create a backup of " + fileToReplace + ".")

                ' Replace the file.
                ReplaceFile(originalFile, fileToReplace, backUpOfFileToReplace)

                Console.WriteLine("Done")

            Else
                Console.WriteLine("Either the file {0} or {1} doesn't " + "exist.", originalFile, fileToReplace)
            End If
        Catch e As Exception
            Console.WriteLine(e.Message)
        End Try

        Console.ReadLine()

    End Sub

    ' Move a file into another file, delete the original, and create a backup of the replaced file.
    Sub ReplaceFile(ByVal fileToMoveAndDelete As String, ByVal fileToReplace As String, ByVal backupOfFileToReplace As String)
        ' Create a new FileInfo object.
        Dim fInfo As New FileInfo(fileToMoveAndDelete)

        ' Replace the file.
        fInfo.Replace(fileToReplace, backupOfFileToReplace, False)

    End Sub
End Module

' Move the contents of test.txt into test2.txt, delete test.txt, and 
' create a backup of test2.txt.
' Done

Comentários

O Replace método substitui o conteúdo de um arquivo especificado pelo conteúdo do arquivo descrito pelo objeto atual FileInfo . Ele também cria um backup do arquivo que foi substituído. Por fim, ele retorna um novo FileInfo objeto que descreve o arquivo substituído.

Passe null para o destinationBackupFileName parâmetro se você não quiser criar um backup do arquivo que está sendo substituído.

Aplica-se a