File.Move Método

Definición

Sobrecargas

Move(String, String)

Mueve un archivo especificado a una nueva ubicación, proporcionando la opción para indicar un nuevo nombre de archivo.

Move(String, String, Boolean)

Mueve un archivo especificado a una nueva ubicación, proporcionando las opciones para especificar un nuevo nombre de archivo y reemplazar el archivo de destino si ya existe.

Move(String, String)

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

Mueve un archivo especificado a una nueva ubicación, proporcionando la opción para indicar un nuevo nombre de archivo.

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

Nombre del archivo que se va a mover. Puede incluir una ruta de acceso relativa o absoluta.

destFileName
String

Nueva ruta de acceso y nombre del archivo.

Excepciones

destFileName ya existe.

o bien

Se ha producido un error de E/S, por ejemplo, al copiar el archivo entre volúmenes de disco.

No se encontró sourceFileName.

sourceFileName o destFileName es null.

Versiones de .NET Framework y .NET Core anteriores a 2.1: sourceFileName o destFileName es una cadena de longitud cero, solo contiene espacios en blanco o contienen caracteres no válidos. Puede consultar los caracteres no válidos con el método GetInvalidPathChars().

El llamador no dispone del permiso requerido.

La ruta de acceso especificada, el nombre de archivo o ambos superan la longitud máxima definida por el sistema.

La ruta de acceso especificada en sourceFileName o destFileName no es válida (por ejemplo, está en una unidad no asignada).

sourceFileName o destFileName está en un formato no válido.

Ejemplos

En el ejemplo siguiente se mueve un archivo.

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

Comentarios

Este método funciona en volúmenes de disco y no produce una excepción si el origen y el destino son los mismos.

Tenga en cuenta que si intenta reemplazar un archivo moviendo un archivo con el mismo nombre en ese directorio, se produce una IOException excepción . Para evitar este problema:

  • En .NET Core 3.0 y versiones posteriores, puede llamar al Move(String, String, Boolean) establecimiento del parámetro overwrite en true, que reemplazará el archivo si existe.

  • En todas las versiones de .NET, puede llamar Copy(String, String, Boolean) a para copiar con sobrescritura y, a continuación, llamar Delete a para quitar el archivo de origen excesivo. Esta estrategia es aconsejable si el archivo que se copia es pequeño y está buscando una operación de archivo "atómica". Si el Delete archivo se bloquea primero y el sistema o programa se bloquea, el archivo de destino ya no existirá.

  • En todas las versiones de .NET, puede llamar a antes de llamar Delete(String) a Move, que solo eliminará el archivo si existe.

Los sourceFileName argumentos y destFileName pueden incluir información de ruta de acceso relativa o absoluta. La información de ruta de acceso relativa se interpreta como relativa al directorio de trabajo actual. Para obtener el directorio de trabajo actual, consulte GetCurrentDirectory.

Mover el archivo entre volúmenes de disco equivale a copiar el archivo y eliminarlo del origen si la copia se realizó correctamente.

Si intenta mover un archivo entre volúmenes de disco y ese archivo está en uso, el archivo se copia en el destino, pero no se elimina del origen.

Para obtener una lista de tareas de E/S comunes, consulte Tareas de E/S comunes.

Consulte también

Se aplica a

Move(String, String, Boolean)

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

Mueve un archivo especificado a una nueva ubicación, proporcionando las opciones para especificar un nuevo nombre de archivo y reemplazar el archivo de destino si ya existe.

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

Nombre del archivo que se va a mover. Puede incluir una ruta de acceso relativa o absoluta.

destFileName
String

Nueva ruta de acceso y nombre del archivo.

overwrite
Boolean

true para reemplazar el archivo de destino si ya existe; false Lo contrario.

Excepciones

destFileName ya existe y overwrite es false.

o bien

Se ha producido un error de E/S, por ejemplo, al copiar el archivo entre volúmenes de disco.

No se encontró sourceFileName.

sourceFileName o destFileName es null.

Versiones de .NET Framework y .NET Core anteriores a 2.1: sourceFileName o destFileName es una cadena de longitud cero, solo contiene espacios en blanco o contienen caracteres no válidos. Puede consultar los caracteres no válidos con el método GetInvalidPathChars().

El llamador no dispone del permiso requerido.

o bien

El sistema operativo no ha adquirido un acceso exclusivo al archivo de destino.

La ruta de acceso especificada, el nombre de archivo o ambos superan la longitud máxima definida por el sistema.

La ruta de acceso especificada en sourceFileName o destFileName no es válida (por ejemplo, está en una unidad no asignada).

sourceFileName o destFileName está en un formato no válido.

Ejemplos

En el ejemplo siguiente se mueve un archivo.

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

Comentarios

Este método funciona en volúmenes de disco y no produce una excepción si el origen y el destino son los mismos.

Los sourceFileName argumentos y destFileName pueden incluir información de ruta de acceso relativa o absoluta. La información de ruta de acceso relativa se interpreta como relativa al directorio de trabajo actual. Para obtener el directorio de trabajo actual, consulte GetCurrentDirectory.

Mover el archivo entre volúmenes de disco equivale a copiar el archivo y eliminarlo del origen si la copia se realizó correctamente.

Si intenta mover un archivo entre volúmenes de disco y ese archivo está en uso, el archivo se copia en el destino, pero no se elimina del origen.

Para obtener una lista de tareas de E/S comunes, consulte Tareas de E/S comunes.

Consulte también

Se aplica a