File.Move Metodo

Definizione

Overload

Move(String, String)

Sposta il file specificato in un nuovo percorso, consentendo di specificare per esso un nuovo nome.

Move(String, String, Boolean)

Sposta un file specificato in una nuova posizione, fornendo le opzioni per specificare un nuovo nome file e sostituire il file di destinazione se esiste già.

Move(String, String)

Origine:
File.cs
Origine:
File.cs
Origine:
File.cs

Sposta il file specificato in un nuovo percorso, consentendo di specificare per esso un nuovo nome.

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)

Parametri

sourceFileName
String

Nome del file da spostare. Può includere un percorso relativo o assoluto.

destFileName
String

Nuovo percorso e nome del file.

Eccezioni

destFileName esiste già.

-oppure-

Si è verificato un errore di I/O, ad esempio, durante la copia del file tra volumi di disco.

Il parametro sourceFileName non è stato trovato.

sourceFileName o destFileName è null.

.NET Framework e versioni di .NET Core precedenti a 2.1: sourceFileName o destFileName è una stringa di lunghezza zero, contiene solo spazi vuoti o contiene caratteri non validi. È possibile cercare i caratteri non validi usando il metodo GetInvalidPathChars().

Il chiamante non dispone dell'autorizzazione richiesta.

Il percorso specificato, il nome file o entrambi superano la lunghezza massima definita dal sistema.

Il percorso specificato in sourceFileName o destFileName non è valido (ad esempio, si trova in un'unità non mappata).

Il formato di sourceFileName o destFileName non è valido.

Esempio

Nell'esempio seguente viene spostato un file.

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

Commenti

Questo metodo funziona tra volumi di dischi e non genera un'eccezione se l'origine e la destinazione sono uguali.

Si noti che se si tenta di sostituire un file spostando un file dello stesso nome in tale directory, viene generato un IOException oggetto. Per evitare questo problema:

  • In .NET Core 3.0 e versioni successive è possibile chiamare Move(String, String, Boolean) l'impostazione del parametro overwrite su true, che sostituirà il file se presente.

  • In tutte le versioni .NET è possibile chiamare Copy(String, String, Boolean) per copiare con sovrascrivere, quindi chiamare Delete per rimuovere il file di origine in eccesso. Questa strategia è consigliabile se il file copiato è piccolo e si sta cercando un'operazione di file "atomica". Se si esegue Delete prima il file e il sistema o il programma si arresta in modo anomalo, il file di destinazione non esiste più.

  • In tutte le versioni .NET è possibile chiamare prima di chiamare Delete(String)Move, che eliminerà solo il file se presente.

Gli sourceFileName argomenti e destFileName possono includere informazioni sul percorso relativo o assoluto. Le informazioni relative sul percorso sono interpretate come relative alla directory di lavoro corrente. Per ottenere la directory di lavoro corrente, vedere GetCurrentDirectory.

Lo spostamento del file tra volumi di disco equivale a copiare il file ed eliminarlo dall'origine se la copia ha avuto esito positivo.

Se si tenta di spostare un file tra volumi di disco e tale file è in uso, il file viene copiato nella destinazione, ma non viene eliminato dall'origine.

Per un elenco di attività di I/O comuni, vedere Attività di I/O comuni.

Vedi anche

Si applica a

Move(String, String, Boolean)

Origine:
File.cs
Origine:
File.cs
Origine:
File.cs

Sposta un file specificato in una nuova posizione, fornendo le opzioni per specificare un nuovo nome file e sostituire il file di destinazione se esiste già.

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)

Parametri

sourceFileName
String

Nome del file da spostare. Può includere un percorso relativo o assoluto.

destFileName
String

Nuovo percorso e nome del file.

overwrite
Boolean

true per sostituire il file di destinazione se esiste già; false Altrimenti.

Eccezioni

destFileName esiste già e overwrite è false.

-oppure-

Si è verificato un errore di I/O, ad esempio, durante la copia del file tra volumi di disco.

Il parametro sourceFileName non è stato trovato.

sourceFileName o destFileName è null.

.NET Framework e versioni di .NET Core precedenti a 2.1: sourceFileName o destFileName è una stringa di lunghezza zero, contiene solo spazi vuoti o contiene caratteri non validi. È possibile cercare i caratteri non validi usando il metodo GetInvalidPathChars().

Il chiamante non dispone dell'autorizzazione richiesta.

-oppure-

Il sistema operativo non è riuscito a acquisire un accesso esclusivo al file di destinazione.

Il percorso specificato, il nome file o entrambi superano la lunghezza massima definita dal sistema.

Il percorso specificato in sourceFileName o destFileName non è valido (ad esempio, si trova in un'unità non mappata).

Il formato di sourceFileName o destFileName non è valido.

Esempio

Nell'esempio seguente viene spostato un file.

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

Commenti

Questo metodo funziona tra volumi di dischi e non genera un'eccezione se l'origine e la destinazione sono uguali.

Gli sourceFileName argomenti e destFileName possono includere informazioni sul percorso relativo o assoluto. Le informazioni relative sul percorso sono interpretate come relative alla directory di lavoro corrente. Per ottenere la directory di lavoro corrente, vedere GetCurrentDirectory.

Lo spostamento del file tra volumi di disco equivale a copiare il file ed eliminarlo dall'origine se la copia ha avuto esito positivo.

Se si tenta di spostare un file tra volumi di disco e tale file è in uso, il file viene copiato nella destinazione, ma non viene eliminato dall'origine.

Per un elenco di attività di I/O comuni, vedere Attività di I/O comuni.

Vedi anche

Si applica a