다음을 통해 공유


File.Move 메서드

정의

오버로드

Name Description
Move(String, String)

지정된 파일을 새 위치로 이동하여 새 파일 이름을 지정하는 옵션을 제공합니다.

Move(String, String, Boolean)

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

Move(String, String)

Source:
File.cs
Source:
File.cs
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 또는 destFileName .입니다 null.

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

호출자에게 필요한 권한이 없습니다.

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

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

sourceFileName 또는 destFileName 잘못된 형식입니다.

예제

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

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 할 수 있습니다. 시스템 또는 프로그램 크래 Copy 시가 부분적으로 작성된 대상 파일을 남길 수 있지만( 불완전할 수 있는) 파일이 항상 대상에 존재하게 되므로 이 전략은 원자적이지 않습니다.

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

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

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

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

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

추가 정보

적용 대상

Move(String, String, Boolean)

Source:
File.cs
Source:
File.cs
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 또는 destFileName .입니다 null.

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

호출자에게 필요한 권한이 없습니다.

-또는-

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

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

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

sourceFileName 또는 destFileName 잘못된 형식입니다.

예제

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

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 작업을 참조하세요.

추가 정보

적용 대상