File.Move Metoda

Definicja

Przeciążenia

Move(String, String)

Przenosi określony plik do nowej lokalizacji, podając opcję określenia nowej nazwy pliku.

Move(String, String, Boolean)

Przenosi określony plik do nowej lokalizacji, podając opcje określania nowej nazwy pliku i zastąpienia pliku docelowego, jeśli już istnieje.

Move(String, String)

Źródło:
File.cs
Źródło:
File.cs
Źródło:
File.cs

Przenosi określony plik do nowej lokalizacji, podając opcję określenia nowej nazwy pliku.

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)

Parametry

sourceFileName
String

Nazwa pliku do przeniesienia. Może zawierać ścieżkę względną lub bezwzględną.

destFileName
String

Nowa ścieżka i nazwa pliku.

Wyjątki

destFileName już istnieje.

-lub-

Wystąpił błąd we/wy, np. podczas kopiowania pliku między woluminami dysku.

sourceFileName nie znaleziono.

sourceFileName lub destFileName to null.

.NET Framework i .NET Core w wersjach starszych niż 2.1: sourceFileName lub destFileName jest ciągiem o zerowej długości, zawiera tylko białe znaki lub zawiera nieprawidłowe znaki. Możesz wykonać zapytanie o nieprawidłowe znaki przy użyciu GetInvalidPathChars() metody .

Obiekt wywołujący nie posiada wymaganych uprawnień.

Podana ścieżka, nazwa pliku lub obie przekraczają maksymalną długość zdefiniowaną przez system.

Ścieżka określona w sourceFileName pliku lub destFileName jest nieprawidłowa (na przykład znajduje się na niemapowanym dysku).

sourceFileName lub destFileName jest w nieprawidłowym formacie.

Przykłady

Poniższy przykład przenosi plik.

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

Uwagi

Ta metoda działa na woluminach dysków i nie zgłasza wyjątku, jeśli źródło i miejsce docelowe są takie same.

Pamiętaj, że jeśli spróbujesz zastąpić plik, przenosząc plik o tej samej nazwie do tego katalogu, IOException zostanie zgłoszony element . Aby uniknąć tego problemu:

  • W programach .NET Core 3.0 i nowszych można wywołać Move(String, String, Boolean) ustawienie parametru overwrite na true, który zastąpi plik, jeśli istnieje.

  • We wszystkich wersjach platformy .NET można wywołać metodę Copy(String, String, Boolean) kopiowania za pomocą zastępowania, a następnie wywołać metodę Delete usuwania nadmiarowego pliku źródłowego. Ta strategia jest zalecana, jeśli skopiowany plik jest mały i szukasz operacji "niepodzielnej". Delete Jeśli plik najpierw ulegnie awarii, a system lub program ulegnie awarii, plik docelowy nie będzie już istnieć.

  • We wszystkich wersjach platformy .NET można wywołać wywołanie przed wywołaniem Delete(String)Movemetody , co spowoduje usunięcie pliku tylko wtedy, gdy istnieje.

Argumenty sourceFileName i destFileName mogą zawierać informacje o ścieżce względnej lub bezwzględnej. Informacje o ścieżce względnej są interpretowane jako względne w stosunku do bieżącego katalogu roboczego. Aby uzyskać bieżący katalog roboczy, zobacz GetCurrentDirectory.

Przeniesienie pliku między woluminami dysku jest równoważne skopiowaniu pliku i usunięciu go ze źródła, jeśli kopiowanie zakończyło się pomyślnie.

Jeśli spróbujesz przenieść plik między woluminami dysku i jest on używany, plik zostanie skopiowany do miejsca docelowego, ale nie zostanie usunięty ze źródła.

Aby uzyskać listę typowych zadań we/wy, zobacz Typowe zadania we/wy.

Zobacz też

Dotyczy

Move(String, String, Boolean)

Źródło:
File.cs
Źródło:
File.cs
Źródło:
File.cs

Przenosi określony plik do nowej lokalizacji, podając opcje określania nowej nazwy pliku i zastąpienia pliku docelowego, jeśli już istnieje.

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)

Parametry

sourceFileName
String

Nazwa pliku do przeniesienia. Może zawierać ścieżkę względną lub bezwzględną.

destFileName
String

Nowa ścieżka i nazwa pliku.

overwrite
Boolean

true zastąpić plik docelowy, jeśli już istnieje; false Inaczej.

Wyjątki

destFileName już istnieje i overwrite jest false.

-lub-

Wystąpił błąd we/wy, np. podczas kopiowania pliku między woluminami dysku.

sourceFileName nie znaleziono.

sourceFileName lub destFileName to null.

.NET Framework i .NET Core w wersjach starszych niż 2.1: sourceFileName lub destFileName jest ciągiem o zerowej długości, zawiera tylko białe znaki lub zawiera nieprawidłowe znaki. Możesz wykonać zapytanie o nieprawidłowe znaki przy użyciu GetInvalidPathChars() metody .

Obiekt wywołujący nie posiada wymaganych uprawnień.

-lub-

System operacyjny nie uzyskał wyłącznego dostępu do pliku docelowego.

Podana ścieżka, nazwa pliku lub obie przekraczają maksymalną długość zdefiniowaną przez system.

Ścieżka określona w sourceFileName pliku lub destFileName jest nieprawidłowa (na przykład znajduje się na niemapowanym dysku).

sourceFileName lub destFileName jest w nieprawidłowym formacie.

Przykłady

Poniższy przykład przenosi plik.

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

Uwagi

Ta metoda działa na woluminach dysków i nie zgłasza wyjątku, jeśli źródło i miejsce docelowe są takie same.

Argumenty sourceFileName i destFileName mogą zawierać informacje o ścieżce względnej lub bezwzględnej. Informacje o ścieżce względnej są interpretowane jako względne w stosunku do bieżącego katalogu roboczego. Aby uzyskać bieżący katalog roboczy, zobacz GetCurrentDirectory.

Przeniesienie pliku między woluminami dysku jest równoważne skopiowaniu pliku i usunięciu go ze źródła, jeśli kopiowanie zakończyło się pomyślnie.

Jeśli spróbujesz przenieść plik między woluminami dysku i jest on używany, plik zostanie skopiowany do miejsca docelowego, ale nie zostanie usunięty ze źródła.

Aby uzyskać listę typowych zadań we/wy, zobacz Typowe zadania we/wy.

Zobacz też

Dotyczy