File.Move 메서드

정의

오버로드

Move(String, String)

지정된 파일을 새 위치로 이동하고 새 파일의 이름을 지정할 수 있는 옵션을 제공합니다.

Move(String, String, Boolean)

지정된 파일을 새 위치로 이동하여 새 파일 이름을 지정하고 이미 있는 경우 대상 파일을 바꿀 수 있는 옵션을 제공합니다.

Move(String, String)

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

지정된 파일을 새 위치로 이동하고 새 파일의 이름을 지정할 수 있는 옵션을 제공합니다.

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)

매개 변수

sourceFileName
String

이동할 파일의 이름입니다. 상대 또는 절대 경로가 포함될 수 있습니다.

destFileName
String

파일에 대한 새 경로 및 이름입니다.

예외

destFileName가 이미 있는 경우

또는

예를 들어 디스크 볼륨에서 파일을 복사하는 동안 I/O 오류가 발생했습니다.

sourceFileName을 찾을 수 없습니다.

sourceFileName 또는 destFileNamenull인 경우

2.1보다 오래된 .NET Framework 및 .NET Core 버전: sourceFileName 또는 destFileName 가 길이가 0인 문자열이거나, 공백만 포함하거나, 잘못된 문자를 포함합니다. GetInvalidPathChars() 메서드를 사용하여 잘못된 문자를 쿼리할 수 있습니다.

호출자에게 필요한 권한이 없는 경우

지정된 경로, 파일 이름 또는 둘 다가 시스템에서 정의한 최대 길이를 초과합니다.

sourceFileName 또는 destFileName에 지정된 경로가 잘못되었습니다(예: 매핑되지 않은 드라이브에 있음).

sourceFileName 또는 destFileName의 형식이 잘못되었습니다.

예제

다음 예제에서는 파일을 이동합니다.

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

설명

이 메서드는 디스크 볼륨에서 작동하며 원본과 대상이 동일한 경우 예외를 throw하지 않습니다.

같은 이름의 파일을 해당 디렉터리로 이동하여 파일을 바꾸려고 하면 이 IOException throw됩니다. 이 문제를 방지하려면 다음을 수행해야 합니다.

  • .NET Core 3.0 이상 버전에서는 매개 변수 overwrite 설정을 로 호출 Move(String, String, Boolean)true수 있습니다. 그러면 파일이 있는 경우 해당 파일이 바뀝니다.

  • 모든 .NET 버전에서 를 호출 Copy(String, String, Boolean) 하여 덮어쓰기를 사용하여 복사한 다음 를 호출 Delete 하여 초과 원본 파일을 제거할 수 있습니다. 복사되는 파일이 작고 "원자성" 파일 작업을 찾고 있는 경우 이 전략을 사용하는 것이 좋습니다. Delete 파일을 먼저 사용하고 시스템 또는 프로그램이 충돌하는 경우 대상 파일이 더 이상 존재하지 않습니다.

  • 모든 .NET 버전에서는 를 호출하기 전에 를 호출 Delete(String)Move할 수 있습니다. 이 호출은 파일이 있는 경우에만 삭제됩니다.

destFileName 인수에는 sourceFileName 상대 또는 절대 경로 정보가 포함될 수 있습니다. 상대 경로 정보는 현재 작업 디렉터리를 기준으로 해석됩니다. 현재 작업 디렉터리를 가져오려면 를 참조하세요 GetCurrentDirectory.

디스크 볼륨 간에 파일을 이동하는 것은 파일을 복사하고 복사에 성공한 경우 원본에서 삭제하는 것과 같습니다.

디스크 볼륨 간에 파일을 이동하려고 하고 해당 파일이 사용 중인 경우 파일이 대상으로 복사되지만 원본에서 삭제되지는 않습니다.

일반적인 I/O 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

Move(String, String, Boolean)

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

지정된 파일을 새 위치로 이동하여 새 파일 이름을 지정하고 이미 있는 경우 대상 파일을 바꿀 수 있는 옵션을 제공합니다.

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)

매개 변수

sourceFileName
String

이동할 파일의 이름입니다. 상대 또는 절대 경로가 포함될 수 있습니다.

destFileName
String

파일에 대한 새 경로 및 이름입니다.

overwrite
Boolean

true 대상 파일이 이미 있는 경우 를 바꿉니다. false 그렇지 않으면.

예외

destFileName 이 이미 있고 overwritefalse입니다.

또는

예를 들어 디스크 볼륨에서 파일을 복사하는 동안 I/O 오류가 발생했습니다.

sourceFileName을 찾을 수 없습니다.

sourceFileName 또는 destFileNamenull인 경우

2.1보다 오래된 .NET Framework 및 .NET Core 버전: sourceFileName 또는 destFileName 가 길이가 0인 문자열이거나, 공백만 포함하거나, 잘못된 문자를 포함합니다. GetInvalidPathChars() 메서드를 사용하여 잘못된 문자를 쿼리할 수 있습니다.

호출자에게 필요한 권한이 없는 경우

또는

운영 체제에서 대상 파일에 대한 단독 액세스 권한을 획득하지 못했습니다.

지정된 경로, 파일 이름 또는 둘 다가 시스템에서 정의한 최대 길이를 초과합니다.

sourceFileName 또는 destFileName에 지정된 경로가 잘못되었습니다(예: 매핑되지 않은 드라이브에 있음).

sourceFileName 또는 destFileName의 형식이 잘못되었습니다.

예제

다음 예제에서는 파일을 이동합니다.

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

설명

이 메서드는 디스크 볼륨에서 작동하며 원본과 대상이 동일한 경우 예외를 throw하지 않습니다.

destFileName 인수에는 sourceFileName 상대 또는 절대 경로 정보가 포함될 수 있습니다. 상대 경로 정보는 현재 작업 디렉터리를 기준으로 해석됩니다. 현재 작업 디렉터리를 가져오려면 를 참조하세요 GetCurrentDirectory.

디스크 볼륨 간에 파일을 이동하는 것은 파일을 복사하고 복사에 성공한 경우 원본에서 삭제하는 것과 같습니다.

디스크 볼륨 간에 파일을 이동하려고 하고 해당 파일이 사용 중인 경우 파일이 대상으로 복사되지만 원본에서 삭제되지는 않습니다.

일반적인 I/O 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상