Partilhar via


File.Move Método

Definição

Sobrecargas

Nome Description
Move(String, String)

Move um arquivo especificado para um novo local, fornecendo a opção para especificar um novo nome de arquivo.

Move(String, String, Boolean)

Move um arquivo especificado para um novo local, fornecendo as opções para especificar um novo nome de arquivo e substituir o arquivo de destino se ele já existir.

Move(String, String)

Origem:
File.cs
Origem:
File.cs
Origem:
File.cs
Origem:
File.cs
Origem:
File.cs

Move um arquivo especificado para um novo local, fornecendo a opção para especificar um novo nome de arquivo.

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

Parâmetros

sourceFileName
String

O nome do arquivo a ser movido. Pode incluir um caminho relativo ou absoluto.

destFileName
String

O novo caminho e o nome do arquivo.

Exceções

destFileName já existe.

- ou -

Ocorreu um erro de E/S, por exemplo, ao copiar o arquivo em volumes de disco.

sourceFileName não foi encontrado.

sourceFileName ou destFileName é null.

As versões do .NET Framework e do .NET Core anteriores à 2.1: sourceFileName ou destFileName são uma cadeia de caracteres de comprimento zero, contêm apenas espaço em branco ou contêm caracteres inválidos. Você pode consultar caracteres inválidos usando o GetInvalidPathChars() método.

O chamador não tem a permissão necessária.

O caminho especificado, o nome do arquivo ou ambos excedem o comprimento máximo definido pelo sistema.

O caminho especificado ou sourceFileNamedestFileName inválido (por exemplo, ele está em uma unidade não mapeada).

sourceFileName ou destFileName está em um formato inválido.

Exemplos

O exemplo a seguir move um arquivo.

using System;
using System.IO;

class Test
{
    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";
        string path2 = @"c:\temp2\MyTest.txt";
        try
        {
            if (!File.Exists(path))
            {
                // This statement ensures that the file is created,
                // but the handle is not kept.
                using (FileStream fs = File.Create(path)) {}
            }

            // Ensure that the target does not exist.
            if (File.Exists(path2))	
            File.Delete(path2);

            // Move the file.
            File.Move(path, path2);
            Console.WriteLine("{0} was moved to {1}.", path, path2);

            // See if the original exists now.
            if (File.Exists(path))
            {
                Console.WriteLine("The original file still exists, which is unexpected.");
            }
            else
            {
                Console.WriteLine("The original file no longer exists, which is expected.");
            }			
        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}
open System.IO

let path = @"c:\temp\MyTest.txt"
let path2 = @"c:\temp2\MyTest.txt"

if File.Exists path |> not then
    // This statement ensures that the file is created,
    // but the handle is not kept.
    use _ = File.Create path
    ()

// Ensure that the target does not exist.
if File.Exists path2 then
    File.Delete path2

// Move the file.
File.Move(path, path2)
printfn $"{path} was moved to {path2}."

// See if the original exists now.
if File.Exists path then
    printfn "The original file still exists, which is unexpected."
else
    printfn "The original file no longer exists, which is expected."
Imports System.IO
Imports System.Text

Public Class Test
    Public Shared Sub Main()
        Dim path As String = "c:\temp\MyTest.txt"
        Dim path2 As String = "c:\temp2\MyTest.txt"

        Try
            If File.Exists(path) = False Then
                ' This statement ensures that the file is created,
                ' but the handle is not kept.
                Dim fs As FileStream = File.Create(path)
                fs.Close()
            End If

            ' Ensure that the target does not exist.
            If File.Exists(path2) Then
                File.Delete(path2)
            End If

            ' Move the file.
            File.Move(path, path2)
            Console.WriteLine("{0} moved to {1}", path, path2)

            ' See if the original file exists now.
            If File.Exists(path) Then
                Console.WriteLine("The original file still exists, which is unexpected.")
            Else
                Console.WriteLine("The original file no longer exists, which is expected.")
            End If
        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class

Comentários

Esse método funciona em volumes de disco e não gera uma exceção se a origem e o destino forem os mesmos.

Observe que, se você tentar substituir um arquivo movendo um arquivo com o mesmo nome para esse diretório, um IOException será gerado. Para evitar esse problema:

  • No .NET Core 3.0 e versões posteriores, você pode chamar Move(String, String, Boolean) a configuração do parâmetro overwrite , trueque substitui o arquivo se ele existir.

  • Em todas as versões do .NET, você pode chamar Copy(String, String, Boolean) para copiar com substituição e, em seguida, chamar Delete para remover o arquivo de origem em excesso. Essa estratégia não é atômica, pois um sistema ou uma falha de programa durante o Copy pode deixar um arquivo de destino parcialmente gravado, mas garantirá que um arquivo (possivelmente incompleto) sempre exista no destino.

  • Em todas as versões do .NET, você pode chamar Delete(String) antes de chamar Move, o que só excluirá o arquivo se ele existir.

O sourceFileName e destFileName os argumentos podem incluir informações de caminho relativas ou absolutas. As informações de caminho relativo são interpretadas como relativas ao diretório de trabalho atual. Para obter o diretório de trabalho atual, consulte GetCurrentDirectory.

Mover o arquivo entre volumes de disco é equivalente a copiar o arquivo e excluí-lo da origem se a cópia tiver sido bem-sucedida.

Se você tentar mover um arquivo entre volumes de disco e esse arquivo estiver em uso, o arquivo será copiado para o destino, mas ele não será excluído da origem.

Para obter uma lista de tarefas comuns de E/S, consulte Tarefas comuns de E/S.

Confira também

Aplica-se a

Move(String, String, Boolean)

Origem:
File.cs
Origem:
File.cs
Origem:
File.cs
Origem:
File.cs
Origem:
File.cs

Move um arquivo especificado para um novo local, fornecendo as opções para especificar um novo nome de arquivo e substituir o arquivo de destino se ele já existir.

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

Parâmetros

sourceFileName
String

O nome do arquivo a ser movido. Pode incluir um caminho relativo ou absoluto.

destFileName
String

O novo caminho e o nome do arquivo.

overwrite
Boolean

true para substituir o arquivo de destino se ele já existir; false Caso contrário.

Exceções

destFileName já existe e overwrite é false.

- ou -

Ocorreu um erro de E/S, por exemplo, ao copiar o arquivo em volumes de disco.

sourceFileName não foi encontrado.

sourceFileName ou destFileName é null.

As versões do .NET Framework e do .NET Core anteriores à 2.1: sourceFileName ou destFileName são uma cadeia de caracteres de comprimento zero, contêm apenas espaço em branco ou contêm caracteres inválidos. Você pode consultar caracteres inválidos usando o GetInvalidPathChars() método.

O chamador não tem a permissão necessária.

- ou -

O sistema operacional falhou ao adquirir um acesso exclusivo ao arquivo de destino.

O caminho especificado, o nome do arquivo ou ambos excedem o comprimento máximo definido pelo sistema.

O caminho especificado ou sourceFileNamedestFileName inválido (por exemplo, ele está em uma unidade não mapeada).

sourceFileName ou destFileName está em um formato inválido.

Exemplos

O exemplo a seguir move um arquivo.

using System;
using System.IO;

class Test
{
    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";
        string path2 = @"c:\temp2\MyTest.txt";
        try
        {
            if (!File.Exists(path))
            {
                // This statement ensures that the file is created,
                // but the handle is not kept.
                using (FileStream fs = File.Create(path)) {}
            }

            // Ensure that the target does not exist.
            if (File.Exists(path2))	
            File.Delete(path2);

            // Move the file.
            File.Move(path, path2);
            Console.WriteLine("{0} was moved to {1}.", path, path2);

            // See if the original exists now.
            if (File.Exists(path))
            {
                Console.WriteLine("The original file still exists, which is unexpected.");
            }
            else
            {
                Console.WriteLine("The original file no longer exists, which is expected.");
            }			
        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}
open System.IO

let path = @"c:\temp\MyTest.txt"
let path2 = @"c:\temp2\MyTest.txt"

if File.Exists path |> not then
    // This statement ensures that the file is created,
    // but the handle is not kept.
    use _ = File.Create path
    ()

// Ensure that the target does not exist.
if File.Exists path2 then
    File.Delete path2

// Move the file.
File.Move(path, path2)
printfn $"{path} was moved to {path2}."

// See if the original exists now.
if File.Exists path then
    printfn "The original file still exists, which is unexpected."
else
    printfn "The original file no longer exists, which is expected."
Imports System.IO
Imports System.Text

Public Class Test
    Public Shared Sub Main()
        Dim path As String = "c:\temp\MyTest.txt"
        Dim path2 As String = "c:\temp2\MyTest.txt"

        Try
            If File.Exists(path) = False Then
                ' This statement ensures that the file is created,
                ' but the handle is not kept.
                Dim fs As FileStream = File.Create(path)
                fs.Close()
            End If

            ' Ensure that the target does not exist.
            If File.Exists(path2) Then
                File.Delete(path2)
            End If

            ' Move the file.
            File.Move(path, path2)
            Console.WriteLine("{0} moved to {1}", path, path2)

            ' See if the original file exists now.
            If File.Exists(path) Then
                Console.WriteLine("The original file still exists, which is unexpected.")
            Else
                Console.WriteLine("The original file no longer exists, which is expected.")
            End If
        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class

Comentários

Esse método funciona em volumes de disco e não gera uma exceção se a origem e o destino forem os mesmos.

O sourceFileName e destFileName os argumentos podem incluir informações de caminho relativas ou absolutas. As informações de caminho relativo são interpretadas como relativas ao diretório de trabalho atual. Para obter o diretório de trabalho atual, consulte GetCurrentDirectory.

Mover o arquivo entre volumes de disco é equivalente a copiar o arquivo e excluí-lo da origem se a cópia tiver sido bem-sucedida.

Se você tentar mover um arquivo entre volumes de disco e esse arquivo estiver em uso, o arquivo será copiado para o destino, mas ele não será excluído da origem.

Para obter uma lista de tarefas comuns de E/S, consulte Tarefas comuns de E/S.

Confira também

Aplica-se a