File.Move Método

Definição

Sobrecargas

Move(String, String)

Move um arquivo especificado para um novo local, oferecendo a opção de 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)

Move um arquivo especificado para um novo local, oferecendo a opção de 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 nome do arquivo.

Exceções

destFileName já existe.

- ou -

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

sourceFileName não foi encontrado.

sourceFileName ou destFileName é null.

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

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

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

O caminho especificado em sourceFileName ou destFileName é 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 namespace System;
using namespace System::IO;

int 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.
         FileStream^ fs = File::Create( path );
         if ( fs )
                  delete (IDisposable^)fs;
      }
      
      // 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 );
   }
}
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 de 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 definição do parâmetro overwrite como true, que substituirá o arquivo se ele existir.

  • Em todas as versões do .NET, você pode chamar Copy(String, String, Boolean) para copiar com overwrite e, em seguida, chamar Delete para remover o arquivo de origem em excesso. Essa estratégia será aconselhável se o arquivo que está sendo copiado for pequeno e você estiver procurando uma operação de arquivo "atômica". Se o Delete arquivo primeiro e o sistema ou o programa falharem, o arquivo de destino não existirá mais.

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

Os sourceFileName argumentos e destFileName podem incluir informações de caminho relativas ou absolutas. As informações do 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 equivale 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 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)

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 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 entre volumes de disco.

sourceFileName não foi encontrado.

sourceFileName ou destFileName é null.

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

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 de arquivo, ou ambos excedem o tamanho máximo definido pelo sistema.

O caminho especificado em sourceFileName ou destFileName é 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 namespace System;
using namespace System::IO;

int 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.
         FileStream^ fs = File::Create( path );
         if ( fs )
                  delete (IDisposable^)fs;
      }
      
      // 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 );
   }
}
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.

Os sourceFileName argumentos e destFileName podem incluir informações de caminho relativas ou absolutas. As informações do 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 equivale 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 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